Killing a pthread waiting on a condition variable

pthread_cancel should wake a thread that is blocked in pthread_cond_wait --- this is one of the required cancellation points. If it doesn't work then something is wrong.

The first thing to check is that cancellation is indeed enabled on the target thread --- explicitly call pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&oldstate) on the target thread to make sure. If that doesn't work, then cancellation is broken on your platform and you'll have to resort to alternatives such as setting a "please stop now" flag and signalling the condition variable.

Do not use asynchronous cancellation unless you really know what you are doing --- it can trigger the cancellation in the middle of any operation (e.g. in the middle of setting up a function call stack frame or running a destructor), and thus can leave your code in a thoroughly inconsistent state. Writing async-cancel-safe code is hard.

Incidentally pthread_kill does not kill a thread --- it sends a signal to it.


Do you have access to the queue, and control of the object schema for enqueued items? If so, define a queue object type that when de-queued, instructs the thread that is processing the item to exit gracefully.

Now, to shut down these threads, simply post a number of these "quit" objects to the HEAD of the queue that corresponds to the number of threads that are servicing the queue, and join on the threads.

This seems much cleaner than the "nuclear option" of pthread_cancel/kill.

Tags:

C++

Pthreads