I am using ZThreads to illustrate the question but my question applies to PThreads, Boost Threads and other such threading libraries in C++.
class MyClass: p
A general solution to the kind of question posted can be found in Herb Sutter article: Prefer Using Active Objects Instead of Naked Threads
This permits you to have something like this (excerpt from article):
class Active {
public:
typedef function Message;
private:
Active( const Active& ); // no copying
void operator=( const Active& ); // no copying
bool done; // le flag
message_queue mq; // le queue
unique_ptr thd; // le thread
void Run() {
while( !done ) {
Message msg = mq.receive();
msg(); // execute message
} // note: last message sets done to true
}
In the active object destructor you can have then:
~Active() {
Send( [&]{ done = true; } ); ;
thd->join();
}
This solution promotes a clean thread function exist, and avoids all other issues related to an unclean thread termination.