Today, I was wandering through the land of operating systems. Specifically, I was reviewing the intricacies of threading. I came across something I didn’t really remember from college (it was probably briefly mentioned or brushed under the carpet (as it’s a bit more of an advanced topic).
I came across the question on how pthread_kill() differs from pthread_cancel(). here and here
For background purposes let’s consider pthread_cancel(). If you want to kill a POSIX thread, you really have two choices, asynchronously (consider this a “forced” kill – abruptly stopping the thread at any hardware instruction) or deferred (flagged for cancellation at cancellation point). Assuming the pthread is cancelable (which by default it is, and is type: deferred) then you should use the pthread_cancel() function to halt the thread at a predetermined cancellation point (sleep, sigsuspend, close, creat, pause and more… click the link above).
If you’ve overridden the default with PTHREAD_CANCEL_ASYNCHRONOUS, you have empowered yourself with significantly more control on when the thread will die. This should only be used in instances where the thread is cancel-safe, i.e. when you’re not holding resources, and it’s fine for your thread to die at any moment. IBM has a nice writeup about this under Async-Cancel Safety, here.
To address the third topic, and draw comparisons, let’s consider pthread_kill(). This function is really quite different than the cancelation function above, as pthread_kill() can deliver a variety of signals that may not halt the thread at all. If performed correctly, you can pass an interrupt signal (SIGINT) to a thread and achieve the same outcome as a pthread_cancel(), but you can also provide any other signal notifications to the thread.
In short, if you want a specific thread to handle a specific signal, use pthread_kill() to pass the signal. Otherwise, if you want to kill a thread, you should generally use pthread_cancel().
The description of pthread_kill() in it’s man pages declares:
The pthread_kill() function sends a signal, specified by sig, to a thread, specified by thread. If sig is 0, error checking is performed, but no signal is actually sent.
Some Side-Notes on Cancellation
Cancelability may be defined on a thread using the following functions:
pthread_setcancelstate() – to enable/disable cancelability
pthread_setcanceltype()) – to set thread to asynchronous/deffered cancelability
Also, please play nicely and make sure you restore invariants and release resources upon exiting a thread (returning from the entry function, pthread_exit, or cancelation) by adding cleanup handlers to the cleanup stack.