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.
Related
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.
I've got a setup something a bit like this:
void* work(void*) { while (true) {/*do work*/} return 0;}
class WorkDoer
{
private:
pthread_t id;
public:
WorkDoer() { pthread_create(&id, NULL, work, (void*)this); }
void Shutdown() { pthread_join(id, NULL); /*other cleanup*/ }
}
There's some cases where Shutdown() is called from the main thread, and some other cases where I want to call shutdown from within the thread itself (returning from that thread right after).
The documentation for pthread_join() says that it will return a EDEADLK if the calling thread is the same as the one passed.
My question is: Is that an okay thing to do, and if so is it safe? (thus ignoring the join fail, because I'll be nicely ending the thread in a moment anyways?) Or, is it something that should be avoided?
You can certainly call pthread_join() from the running thread itself, and as you have found out the call itself will handle it properly giving you an error code. However, there are a few problems:
It doesn't make any sense because the join won't join anything. It will merely tell you that you are doing something wrong.
The thread itself won't exit upon calling pthread_join() on itself.
Even if the thread exists, its state won't be cleaned up properly. Some other thread (i.e. your application's main thread) should call pthread_join() unless the thread was created as “detached”.
So in other words this approach is as acceptable as a bug in your program.
As a solution I would recommend to revisit the design and make sure that Shutdown() is called from the right place and at the right time. After all, the name “shutdown” doesn't make a lot of sense here because it doesn't shutdown a thing. What it does is merely waiting for a thread to finish and cleans up its state after that happens.
When you want to end the worker thread, either return from the thread routine or call pthread_exit(). Then make sure that whoever started a thread cleans things up by calling pthread_join().
If you want to force the thread to stop, consider using pthread_kill() to signal a thread or, alternatively, implement some sort of message passing that you can use to "tell" thread to stop doing whatever it is doing.
The pthread_join() function may fail if:
EDEADLK
A deadlock was detected or the value of thread specifies the
calling thread.
I would say use at your own risk.
Why not just let the thread call pthread_detach(pthread_self()); and then exit. No need to call pthread_join() then anymore and risking to have it fail.
I have a method which is fired once every 30 seconds aprox. that I need to have in a thread.
I have a method that I can call from outside the class. Something like callThreadedMethod() which creates the thread which itself calls the final threadedMethod.
These are methods of MyClass
void callThreadedMethod(){
mThread = boost::shared_ptr<boost::thread>(new boost::thread(&MyClass::threadedMethod, this));
}
void threadedMethod(){
//more code NOT inside a while loop
}
So do I have to detach mThread every time the method is called?
Is it enough to call join() in the MyClass destructor?
Does the thread destroys itself when threadedMethod finishes?
It depends what you want to achieve. If you don't care when or if the calls to threadedMethod terminate, or whether or not they throw, then you can just detach the thread as soon as you've created it; each thread will be destroyed when the method completes. And you shouldn't store the thread in a member variable.
If you do care then you need to call join on each thread you create (so once per thread, not once in the destructor). I suspect you don't.
Do you really need to create a new thread for each call? Thread creation can be expensive, so an alternative would be to use a thread pool and submit each threadedMethod invocation to that. The pool could then have the lifetime of the MyClass instance. But perhaps that's overkill for something that is only happening once every 30s.
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.