Shared_ptr never deallocated when boost threads created - c++

So I have a strange situation here. I have the following code:
int main()
{
std::shared_ptr<MyClassA> classA = std::shared_ptr<MyClassA>(new MyClassA);
std::shared_ptr<MyClassB> classB = std::shared_ptr<MyClassB>(new MyClassB(classA));
boost::thread_group threadGroup;
// This thread is essentially an infinite loop waiting for data on a socket
threadGroup.create_thread( boost::bind(&MyClassB::method1, classB) );
...do stuff
return 0;
}
MyClassB opens several resources, that are not deallocated when the program exits. However, if I remove the call to create_thread, the resources are deallocated. I put a printout in the destructor of MyClassB, and verified that it's not being called if that thread is created.
Anybody have any insight into what's going on here?

According to documentation boost::thread_group destructor destroys all onwed thread. boost::thread destructor in order:
if defined BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE: If *this has an associated thread of execution, calls detach(), DEPRECATED
BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE: If the thread is joinable calls to std::terminate. Destroys *this.
So you need to join threads explicitly. You can do that by calling boost::thread_group::join_all() at the end of your program.

Since you are passing shared pointer to class B to your thread, your thread now shares the instance. Until this threads exits NATURALLY, this resource will not be freed.

// This thread is essentially an infinite loop waiting for data on a socket
This comment is very telling. Your thread may run forever, well past the end of the program. If that's the case, you need to detach the thread before you exit main, and you should expect not to see the destructor called. The thread is still alive and shares ownership of that object.
...do stuff
If that ...do stuff doesn't involve either detaching or joining that thread, you are invoking undefined behavior in Boost. That undefined behavior becomes very well defined if you switch from using boost::thread to using std::thread.
That well-defined behavior is something that no sane programmer wants to invoke: Destructing a joinable thread results in a call to std::terminate(). The behavior of std::terminate is implementation-dependent, but typically it means "stop right now". Destructors aren't called, exit handlers aren't called.
You need to either join or detach that thread.

Related

std::thread termination without calling join() [duplicate]

Given below:
void test()
{
std::chrono::seconds dura( 20 );
std::this_thread::sleep_for( dura );
}
int main()
{
std::thread th1(test);
std::chrono::seconds dura( 5 );
std::this_thread::sleep_for( dura );
return 0;
}
main will exit after 5 seconds, what will happen to th1 that's still executing?
Does it continue executing until completion even if the th1 thread object you defined in main goes out of scope and gets destroyed?
Does th1 simply sits there after it's finished executing or somehow gets cleaned up when the program terminates?
What if the thread was created in a function, not main - does the thread stays around until the program terminates or when the function goes out of scope?
Is it safe to simply not call join for a thread if you want some type of timeout behavior on the thread?
If you have not detached or joined a thread when the destructor is called it will call std::terminate, we can see this by going to the draft C++11 standard we see that section 30.3.1.3 thread destructor says:
If joinable(), calls std::terminate(). Otherwise, has no effects. [
Note: Either implicitly detaching or joining a joinable() thread in
its destructor could result in difficult to debug correctness (for
detach) or performance (for join) bugs encountered only when an
exception is raised. Thus the programmer must ensure that the
destructor is never executed while the thread is still joinable. —end
note ]
as for a rationale for this behavior we can find a good summary in (Not) using std::thread
Why does the destructor of a joinable thread have to call
std::terminate? After all, the destructor could join with the child
thread, or it could detach from the child thread, or it could cancel
the thread. In short, you cannot join in the destructor as this would
result in unexpected (not indicated explicitly in the code) program
freeze in case f2 throws.
and an example follows and also says:
You cannot detach as it would risk the situation where main thread
leaves the scope which the child thread was launched in, and the child
thread keeps running and keeps references to the scope that is already
gone.
The article references N2802: A plea to reconsider detach-on-destruction for thread objects which is argument against the previous proposal which was detach on destruction if joinable and it notes that one of the two alternatives would be to join which could lead to deadlocks the other alternative is what we have today which is std::terminate on destruction if joinable.
std::thread::~thread()
If *this has an associated thread (joinable() == true), std::terminate() is called
Source: http://en.cppreference.com/w/cpp/thread/thread/~thread
This means that program like this is not at all well-formed or safe.
Note, however, that boost::thread::~thread() calls detach() instead in this case.
(as user dyp stated in comments, this behavior is deprecated in more recent versions)
You could always workaround this using RAII. Just wrap your thread inside another class, that will have desired behavior on destruction.
In C++11, you must explicitly specify 'what happens' when the newly created thread goes out of scope (our it's dtor is called). Sometimes, when we are sure that the main thread, is continuing, and our threads are acting as 'pipeline', it is safe to 'detach()' them; and sometimes when we are waiting for our WORKER threads to complete their operations, we 'join()' them.
As this says, the programmer must ensure that the destructor is never executed while the thread is still joinable.
Specify your multi-threaded strategy. In this example, std::terminate() is called.

What happens if one deletes an object with a running pthread?

I have an object that uses pthreads. Its constructor creates several threads.
The class's destructor calls pthread_join on all these threads.
What would happen during a delete, if it didn't? I.e., what happens to a non-terminated thread, if the delete operator suddenly tries to deallocate the object?
Thanks in advance for all replies. :)
With the join, your destructor will block until all of the joined threads have exited.
pthread_join
The pthread_join() function waits for the thread specified by thread
to terminate. If that thread has already terminated, then
pthread_join() returns immediately. The thread specified by thread
must be joinable.
If you don't join with the threads, they will continue to run. This can have various consequences depending on if you invoke undefined behavior (eg, try to reference the deleted object after the destructor exits from one of the still running threads).
Deleting the pthread_t objects could have consequences depending on your system (I don't know every implementation of pthreads), but in general they're only references to the underlying system object representing the thread. So you will lose your reference to that thread, and potentially be unable to join with it later, but the thread would continue to run.

C++11: What happens if you don't call join() for std::thread

Given below:
void test()
{
std::chrono::seconds dura( 20 );
std::this_thread::sleep_for( dura );
}
int main()
{
std::thread th1(test);
std::chrono::seconds dura( 5 );
std::this_thread::sleep_for( dura );
return 0;
}
main will exit after 5 seconds, what will happen to th1 that's still executing?
Does it continue executing until completion even if the th1 thread object you defined in main goes out of scope and gets destroyed?
Does th1 simply sits there after it's finished executing or somehow gets cleaned up when the program terminates?
What if the thread was created in a function, not main - does the thread stays around until the program terminates or when the function goes out of scope?
Is it safe to simply not call join for a thread if you want some type of timeout behavior on the thread?
If you have not detached or joined a thread when the destructor is called it will call std::terminate, we can see this by going to the draft C++11 standard we see that section 30.3.1.3 thread destructor says:
If joinable(), calls std::terminate(). Otherwise, has no effects. [
Note: Either implicitly detaching or joining a joinable() thread in
its destructor could result in difficult to debug correctness (for
detach) or performance (for join) bugs encountered only when an
exception is raised. Thus the programmer must ensure that the
destructor is never executed while the thread is still joinable. —end
note ]
as for a rationale for this behavior we can find a good summary in (Not) using std::thread
Why does the destructor of a joinable thread have to call
std::terminate? After all, the destructor could join with the child
thread, or it could detach from the child thread, or it could cancel
the thread. In short, you cannot join in the destructor as this would
result in unexpected (not indicated explicitly in the code) program
freeze in case f2 throws.
and an example follows and also says:
You cannot detach as it would risk the situation where main thread
leaves the scope which the child thread was launched in, and the child
thread keeps running and keeps references to the scope that is already
gone.
The article references N2802: A plea to reconsider detach-on-destruction for thread objects which is argument against the previous proposal which was detach on destruction if joinable and it notes that one of the two alternatives would be to join which could lead to deadlocks the other alternative is what we have today which is std::terminate on destruction if joinable.
std::thread::~thread()
If *this has an associated thread (joinable() == true), std::terminate() is called
Source: http://en.cppreference.com/w/cpp/thread/thread/~thread
This means that program like this is not at all well-formed or safe.
Note, however, that boost::thread::~thread() calls detach() instead in this case.
(as user dyp stated in comments, this behavior is deprecated in more recent versions)
You could always workaround this using RAII. Just wrap your thread inside another class, that will have desired behavior on destruction.
In C++11, you must explicitly specify 'what happens' when the newly created thread goes out of scope (our it's dtor is called). Sometimes, when we are sure that the main thread, is continuing, and our threads are acting as 'pipeline', it is safe to 'detach()' them; and sometimes when we are waiting for our WORKER threads to complete their operations, we 'join()' them.
As this says, the programmer must ensure that the destructor is never executed while the thread is still joinable.
Specify your multi-threaded strategy. In this example, std::terminate() is called.

How to safely delete a thread pointer in a destructor?

Say, I have a C++ class including a thread pointer as a member variable. The thread keeps running until the program exits. If I delete the pointer in the destructor, it seems that the thread has not yet finished at that moment? What is the best practice to manage this or any tricks?
Sample code:
class Car {
public:
Car();
~Car();
private:
boost::thread *m_runningThreadPtr;
};
Car::Car() {
m_runningThreadPtr = new boost::thread();
}
Car::~Car() {
delete m_runningThreadPtr; // The thread should be still running now.
// Problematic if it was deleted here?
}
By default the destructor will call terminate() to kill the thread if it's still running, whether this is safe or not depends on what the thread is doing at the time. You can call join() before deleting it if you want to wait for the thread to finish, and use some sort of synchronization system (even just a global flag) that tells the thread to quit.
It depends on what kind of behavior you're looking for.
If you want to delete the object, and have it stop its owned thread and then delete its thread object, then you should have a stop flag which your thread checks from time to time. In the destructor, you'd set the stop flag, and then call join() on your thread. Once it returns, you can safely delete the pointer.
If, on the other hand, you want to delete the object and have the thread go on its own until it finishes, then you need a more clever mechanism, like at the end of your thread function, posting to the main thread of your application a callback that calls join() on your thread and then deletes it. For that, of course, you'll need to have in your thread function a pointer to your thread object.
EDIT
In the case of boost::thread, it simply detaches in its destructor, so for the second option you can safely delete it when you're done.
It's important to note, however, that this won't work with std::thread's destructor, which will terminate your program in such a case. But then you can also manually call detach() and then delete. So you really have to look at the API you're using.
Don't delete it. Have the thread delete itself when done.
Your program is done when there's no more code to run. Are your threads still running code? Then why do you think your program is done?
So, it's reasonable to assume your threads are i fact done. That means you can call .join() on the thread, after which it is OK to call delete.

What’s the best way to delete boost::thread object right after its work is complete?

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