Next: Cleanup Handlers, Previous: Thread Attributes, Up: POSIX Threads
Cancellation is the mechanism by which a thread can terminate the
execution of another thread. More precisely, a thread can send a
cancellation request to another thread. Depending on its settings, the
target thread can then either ignore the request, honor it immediately,
or defer it till it reaches a cancellation point. When threads are
first created by pthread_create, they always defer cancellation
requests.
When a thread eventually honors a cancellation request, it behaves as if
pthread_exit(PTHREAD_CANCELED) was called. All cleanup handlers
are executed in reverse order, finalization functions for
thread-specific data are called, and finally the thread stops executing.
If the canceled thread was joinable, the return value
PTHREAD_CANCELED is provided to whichever thread calls
pthread_join on it. See pthread_exit for more information.
Cancellation points are the points where the thread checks for pending
cancellation requests and performs them. The POSIX threads functions
pthread_join, pthread_cond_wait,
pthread_cond_timedwait, pthread_testcancel,
sem_wait, and sigwait are cancellation points. In
addition, these system calls are cancellation points:
| accept | open | sendmsg
|
| close | pause | sendto
|
| connect | read | system
|
| fcntl | recv | tcdrain
|
| fsync | recvfrom | wait
|
| lseek | recvmsg | waitpid
|
| msync | send | write
|
| nanosleep
|
All library functions that call these functions (such as
printf) are also cancellation points.
pthread_setcancelstatechanges the cancellation state for the calling thread – that is, whether cancellation requests are ignored or not. The state argument is the new cancellation state: eitherPTHREAD_CANCEL_ENABLEto enable cancellation, orPTHREAD_CANCEL_DISABLEto disable cancellation (cancellation requests are ignored).If oldstate is not
NULL, the previous cancellation state is stored in the location pointed to by oldstate, and can thus be restored later by another call topthread_setcancelstate.If the state argument is not
PTHREAD_CANCEL_ENABLEorPTHREAD_CANCEL_DISABLE,pthread_setcancelstatefails and returnsEINVAL. Otherwise it returns 0.
pthread_setcanceltypechanges the type of responses to cancellation requests for the calling thread: asynchronous (immediate) or deferred. The type argument is the new cancellation type: eitherPTHREAD_CANCEL_ASYNCHRONOUSto cancel the calling thread as soon as the cancellation request is received, orPTHREAD_CANCEL_DEFERREDto keep the cancellation request pending until the next cancellation point. If oldtype is notNULL, the previous cancellation state is stored in the location pointed to by oldtype, and can thus be restored later by another call topthread_setcanceltype.If the type argument is not
PTHREAD_CANCEL_DEFERREDorPTHREAD_CANCEL_ASYNCHRONOUS,pthread_setcanceltypefails and returnsEINVAL. Otherwise it returns 0.