What is the state of thread after it completes its execution.?
Is it destroyed immediately after its execution or is it destroyed with parent thread.?
The std::thread object is different than a underlying thread of control (although they should map 1-on-1).
This separation is really important and it implies that std::thread and thread of control can have different life duration. For example, if you create your std::thread on the stack, you really need to call thread::detach before your object go destroyed (if you don't destructor will call terminate ). Also, as Grizzly pointed out, you can call .join() before your object destruction which will block until the execution of the thread has finished.
This also answers your question - std::thread object is not destroyed after the thread is finished - it is behaving as every other C++ object - it will be destroyed when it goes out of the scope (or gets deleted).
Related
I was wondering what would happen in such a class:
class MyClass
{
private:
std::vector<int> iVector;
void Worker()
{
//Lots of stuff done with iVector
//adding, removing elements, etc.
}
}
Let's say I create a thread (invoked by one of the class member functions) that uses iVector and modifies it. Besides this worker, none of the other member functions of the class reads or modifies this std::vector.
Everything seems fine as worker thread is the only one using iVector.
But what would happen when one instance of the object is destroyed? Even if the object is destroyed after the worker thread is finished, destructor for iVector would be invoked from the main thread. Would this lead to undefined behavior?
Thanks!
Firstly I would suggest running a std::join (or your library equivalent) on the thread in the destructor. This will ensure the thread is properly finished and synchronized before the vector destructor runs. This is important as the vector's lifetime must exceed the thread using it.
The C++11 standard and presumably later ones state in 30.3.1.5:
5: Synchronization: The completion of the thread represented by *this
synchronizes with (1.10) the corresponding successful join() return. [
Note: Operations on *this are not synchronized. — end note ]
Now we have to examine 1.10 for more detail, first this section states:
3: The value of an object visible to a thread T at a particular point
is the initial value of the object, a value assigned to the object by
T, or a value assigned to the object by another thread, according to
the rules below.
Honestly, this is difficult to parse, it does not specify exactly what kind of synchronization join offers and seems to imply it synchronizes only the thread itself and not data it has accessed. Therefore I would go the safe route and run atomic_thread_fence(memory_order_acquire) after join in the main thread, and atomic_thread_fence(memory_order_release) in the child thread just before it finishes which should guarantee full happens before semantics and no UB.
If an execution thread is using the ivector class member, and another thread destroys the object with this class member, the continued use of the ivector class member results in undefined behavior.
Even if the object is destroyed after the worker thread is finished,
destructor for iVector would be invoked from the main thread. Would
this lead to undefined behavior?
No. As you've described, this situation is not undefined behavior. The C++ standard does not require an object to be destroyed by the same execution thread that created the object. It's fine for one execution thread to grow, resize the vector, then go away or stop using the vector, and then a different execution thread destroy the entire object.
I am currently creating a program which calls native code from within a java environment (NDK).
I have a function that is going to be called a few times from my java code. In this function I create a detached thread that will act as a timer to stop a particular function in my native code.
The code looks like this:
void myNativeFunction(){
std::thread timerTrial(&FluidMechanics::Impl::endTrial,this);
timerTrial.detach();
}
void endTrial(){
//code here
return ;
}
The thing is that when endTrial returns I was wondering whether my thread was going to be terminated and all resources freed when I return. Indeed myNativeFunction will be called again a couple of times shortly after that so I don't want to mess up my ressources and memory.
Yes. Any thread specific resources will be automatically released when the detached thread returns.
C++11 draft, N3690, § 30.3.1.7, 10, detach()
The thread represented by *this continues execution without the
calling thread blocking. When detach() returns, *this no longer
represents the possibly continuing thread of execution. When the
thread previously represented by *this ends execution, the
implementation shall release any owned resources.
(emphasis mine).
I'm trying to create a thread with the regular c++11 threads.
I have an object called NetworkManager that creates a thread of one of its methods in its constructor like this:
void NetworkManager()
{
// Raknet setup here...
std::thread networkUpdate(&NetworkManager::update, this);
// Set timers
playerDataTimer.start();
playerDataTimer.pause();
Logger::log("NetworkManager constructor ended");
}
The update method handles the messages coming on from other clients via the RakNet library like here: Link
I did the same thing as in the example where it's encapsulated in a while loop that keeps going forever.
When I try to create this thread in the constructor however I get an abort() message (the application crashes) and I can't figure out why this is. All objects that are used in the thread are setup before the loop starts so I don't think that's the issue.
The std::thread object you're creating gets destroyed at the end of your constructor since it is a local variable. If the destructor of a std::thread is called while the thread is joinable (like it is in your example), std::terminate is called.
You must keep that thread object as a member of your class, or store it somewhere else, or detach the thread. (Or join with it in your constructor, but that doesn't sound like it would do what you want.)
Your app terminates because the std::thread is destructed without being .detached or .joined.
~thread();
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.
I create boost::thread object with a new operator and continue without waiting this thread to finish its work:
void do_work()
{
// perform some i/o work
}
boost::thread *thread = new boost::thread(&do_work);
I guess, it’s necessary to delete thread when the work is done. What’s the best way to this without explicitly waiting for thread termination?
The boost::thread object's lifetime and the native thread's lifetime are unrelated. The boost::thread object can go out of scope at any time.
From the boost::thread class documentation
Just as the lifetime of a file may be different from the lifetime of an iostream object which represents the file, the lifetime of a thread of execution may be different from the thread object which represents the thread of execution. In particular, after a call to join(), the thread of execution will no longer exist even though the thread object continues to exist until the end of its normal lifetime. The converse is also possible; if a thread object is destroyed without join() having first been called, the thread of execution continues until its initial function completes.
Edit: If you just need to start a thread and never invoke join, you can use the thread's constructor as a function:
// Launch thread.
boost::thread(&do_work);
However, I don't suggest you do that, even if you think you're sure the thread will complete before main() does.
You can use
boost::thread t(&do_work);
t.detach();
Once the thread is detached it is no longer owned by the boost::thread object; the object can be destroyed and the thread will continue to run. The boost::thread destructor also calls detach() if the object owns a running thread, so letting t get destroyed will have the same result.
I suggest you use boost::shared_ptr, so you won't take care when to delete thread object.
boost::shared_ptr<boost::thread> thread(new boost::thread(&do_work));
You should take a look at thread interruption.
This article is good also.
http://www.boost.org/doc/libs/1_38_0/doc/html/thread/thread_management.html
I am working on a multithreaded program using C++ and Boost. I am using a helper thread to eagerly initialize a resource asynchronously. If I detach the thread and all references to the thread go out of scope, have I leaked any resources? Or does the thread clean-up after itself (i.e. it's stack and any other system resources needed for the itself)?
From what I can see in the docs (and what I recall from pthreads 8 years ago), there's not explicit "destory thread" call that needs to be made.
I would like the thread to execute asynchronously and when it comes time to use the resource, I will check if an error has occured. The rough bit of code would look something like:
//Assume this won't get called frequently enough that next_resource won't get promoted
//before the thread finishes.
PromoteResource() {
current_resource_ptr = next_resource_ptr;
next_resource_ptr.reset(new Resource());
callable = bind(Resource::Initialize, next_resource); //not correct syntax, but I hope it's clear
boost::thread t(callable);
t.start();
}
Of course--I understand that normal memory-handling problems still exist (forget to delete, bad exception handling, etc)... I just need confirmation that the thread itself isn't a "leak".
Edit: A point of clarification, I want to make sure this isn't technically a leak:
void Run() {
sleep(10 seconds);
}
void DoSomething(...) {
thread t(Run);
t.run();
} //thread detaches, will clean itself up--the thread itself isn't a 'leak'?
I'm fairly certain everything is cleaned up after 10 seconds-ish, but I want to be absolutely certain.
The thread's stack gets cleaned up when it exits, but not anything else. This means that anything it allocated on the heap or anywhere else (in pre-existing data structures, for example) will get left when it quits.
Additionally any OS-level objects (file handle, socket etc) will be left lying around (unless you're using a wrapper object which closes them in its destructor).
But programs which frequently create / destroy threads should probably mostly free everything that they allocate in the same thread as it's the only way of keeping the programmer sane.
If I'm not mistaken, on Windows Xp all resources used by a process will be released when the process terminates, but that isn't true for threads.
Yes, the resources are automatically released upon thread termination. This is a perfectly normal and acceptable thing to do to have a background thread.
To clean up after a thread you must either join it, or detach it (in which case you can no longer join it).
Here's a quote from the boost thread docs that somewhat explains that (but not exactly).
When the boost::thread object that
represents a thread of execution is
destroyed the thread becomes detached.
Once a thread is detached, it will
continue executing until the
invocation of the function or callable
object supplied on construction has
completed, or the program is
terminated. A thread can also be
detached by explicitly invoking the
detach() member function on the
boost::thread object. In this case,
the boost::thread object ceases to
represent the now-detached thread, and
instead represents Not-a-Thread.
In order to wait for a thread of
execution to finish, the join() or
timed_join() member functions of the
boost::thread object must be used.
join() will block the calling thread
until the thread represented by the
boost::thread object has completed. If
the thread of execution represented by
the boost::thread object has already
completed, or the boost::thread object
represents Not-a-Thread, then join()
returns immediately. timed_join() is
similar, except that a call to
timed_join() will also return if the
thread being waited for does not
complete when the specified time has
elapsed.
In Win32, as soon as the thread's main function, called ThreadProc in the documentation, finishes, the thread is cleaned up. Any resources allocated by you inside the ThreadProc you'll need to clean up explicitly, of course.