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_setcancelstate
changes 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_ENABLE
to enable cancellation, orPTHREAD_CANCEL_DISABLE
to 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_ENABLE
orPTHREAD_CANCEL_DISABLE
,pthread_setcancelstate
fails and returnsEINVAL
. Otherwise it returns 0.
pthread_setcanceltype
changes 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_ASYNCHRONOUS
to cancel the calling thread as soon as the cancellation request is received, orPTHREAD_CANCEL_DEFERRED
to 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_DEFERRED
orPTHREAD_CANCEL_ASYNCHRONOUS
,pthread_setcanceltype
fails and returnsEINVAL
. Otherwise it returns 0.