views:

1175

answers:

3

In my destructor I want to destroy a thread cleanly.

My goal is to wait for a thread to finish executing and THEN destroy the thread.

The only thing I found about querying the state of a pthread is pthread_attr_setdetachstate but this only tells you if your thread is:

  • PTHREAD_CREATE_DETACHED
  • PTHREAD_CREATE_JOINABLE

Both of those have nothing to do with whether the thread is still running or not.

How do you query a pthread to see if it is still running?

+1  A: 

There is not fully portable solution, look if your platform supports pthread_tryjoin_np or pthread_timedjoin_np. So you just check if thread can be joined (of course created with PTHREAD_CREATE_JOINABLE).

Dewfy
+2  A: 

I think all you really need is to call pthread_join(). That call won't return until the thread has exited.

If you only want to poll to see whether the thread is still running or not (and note that is usually not what you should be wanting to do!), you could have the thread set a volatile boolean to false just before it exits... then your main-thread could read the boolean and if it's still true, you know the thread is still running. (if it's false, on the other hand, you know the thread is at least almost gone; it may still be running cleanup code that occurs after it sets the boolean to false, though, so even in this case you should still call pthread_join before trying to free any resources the thread might have access to)

Jeremy Friesner
+5  A: 

It sounds like you have two questions here:

How can I wait until my thread completes?

Answer: This is directly supported by pthreads -- make your thread-to-be-stopped JOINABLE (when it is first started), and use pthread_join() to block your current thread until the thread-to-be-stopped is no longer running.


How can I tell if my thread is still running?

Answer: You can add a "thread_complete" flag to do the trick:

Scenario: Thread A wants to know if Thread B is still alive.

When Thread B is created, it is given a pointer to the "thread_complete" flag address. The "thread_complete" flag should be initialized to NOT_COMPLETED before the thread is created. Thread B's entry point function should immediately call pthread_cleanup_push() to push a "cleanup handler" which sets the "thread_complete" flag to COMPLETED.

See details about cleanup handlers here: pthread cleanup handlers

You'll want to include a corresponding pthread_cleanup_pop(1) call to ensure that the cleanup handler gets called no matter what (i.e. if the thread exits normally OR due to cancellation, etc.).

Then, Thread A can simply check the "thread_complete" flag to see if Thread B has exited yet.

NOTE: Your "thread_complete" flag should be declared "volatile" and should be an atomic type -- the GNU compilers provide the sig_atomic_t for this purpose. This allows the two threads consistent access the same data without the need for synchronization constructs (mutexes/semaphores).

jeremytrimble