Thread cancellation
When multiple threads are running in a process, thread cancellation permits one thread to cancel another thread in that process. This is done with the pthread_cancel() function, which causes the system to generate a cancel interrupt and direct it to the thread specified on the pthread_cancel(). Each thread can control how the system generates this cancel interrupt by altering the interrupt state and type.
- disabled
- For short code sequences, the entire code sequence can be disabled to prevent cancel interrupts. The pthread_setintr() and pthread_setcancelstate() functions enable or disable cancel interrupts in this manner.
- controlled
- For larger code sequences where you want some control over the
interrupts but cannot be entirely disabled, set the interrupt type
to controlled/deferred and the interrupt state to enabled. The pthread_setintrtype() and pthread_setcanceltype() functions
allow for this type of managed interrupt delivery by introducing the
concept of cancellation points.
Cancellation points consist of calls to a limited set of library functions, documented below.
The user program can implicitly or explicitly solicit interrupts by invoking one of the library functions in the set of cancellation points, thus allowing the user to control the points within their application where a cancel may occur.
- asynchronous
- For code sequences where you do not need any control over the interrupt, set pthread_setintr()/pthread_setcancelstate() to enable and pthread_setintrtype()/pthread_setcanceltype() to asynchronous. This will allow cancel interrupts to occur at any point within your program.
For example, if you have a critical code section (a sequence of code that needs to complete), you would turn cancel off or prevent the sequence from being interrupted. If the code is relatively long, consider running using the control interrupt and as long as the critical code section doesn't contain any of the functions that are considered cancellation points, it will not be unexpectedly canceled.
For C++, destructors for automatic objects on the stack are run when a thread is cancelled. The stack is unwound and the destructors are run in reverse order.