by guenter » 13 May 2008, 14:34
Normallly it should not be a problem to delete the Thread object while the thread is still running. The Thread class has been designed for this and in this case will detach the thread in the destructor. This means, however, that you can't join() the thread from another thread once it has been deleted. Also, Thread::current() will return an invalid pointer once the Thread object has been deleted.
Also, my first response was, uh, crap. While deleting the Thread technically should work, it's not really what I meant to say. The best way to solve this problem is to use the ThreadPool (I wouldn't consider it overkill, since it's there anyway - other parts of POCO use it, and it's really lightweight), and create a Runnable on the heap. Then, at the end of run, do the delete this - deleting the Runnable, not the thread. Now, you could also have the Thread as a member of your Runnable, In this case, the Thread object will be deleted with the Runnable and the underlying OS thread will be detached and run until your Runnable::run() completes. As I said above, join() won't work in this case. If you need some synchronization (tell someone that the thread has finished), use an Event object (stored outside of your Runnable) and set() it at the end of run(). You can wait() on this Event from another thread.
If you use the trunk version from POCO it is also possible to reuse a Thread object. You create the Thread object once and you can call start() multiple times, provided the thread has completed in between calls to start().