## Thread Cancellation

Canceling is a mechanism by which one thread terminates another thread (or itself). When you request that a thread be canceled, you are requesting that it terminate as soon as possible. However, the target thread can control how quickly it terminates by controlling its general cancelability and its asynchronous cancelability.

The following is a list of the pthread calls that are cancellation points:

· The pthread_setasynccancel( ) routine

· The pthread_testcancel( ) routine

· The pthread_delay_np( ) routine

· The pthread_join( ) routine

· The pthread_cond_wait( ) routine

· The pthread_cond_timedwait( ) routine

General cancelability is enabled by default. A thread is canceled only at specific places in the program; for example, when a call to the pthread_cond_wait( ) routine is made. If general cancelability is enabled, request the delivery of any pending cancel request by using the pthread_testcancel( ) routine. This routine allows you to permit cancellation to occur at places where it may not otherwise be permitted under general cancelability, and it is especially useful within very long loops to ensure that cancel requests are noticed within a reasonable time.

If you disable general cancelability, the thread cannot be terminated by any cancel request. Disabling general cancelability means that a thread could wait indefinitely if it does not come to a normal conclusion. Therefore, be careful about disabling general cancelability.

Asynchronous cancelability, when it is enabled, allows cancels to be delivered to the enabling thread at any time, not only at those times that are permitted when just general cancelability is enabled. Thus, use asynchronous cancellation primarily during long processes that do not have specific places for cancel requests. Asynchronous cancelability is disabled by default. Disable asynchronous cancelability when calling threads routines or any other runtime library routines that are not explicitly documented as cancel-safe.

Note: If general cancelability is disabled, the thread cannot be canceled, regardless of whether asynchronous cancelability is enabled or disabled. The setting of asynchronous cancelability is relevant only when general cancelability is enabled.

Use the following routines to control the canceling of threads:

· The pthread_setcancel( ) routine to enable and disable general cancelability

· The pthread_testcancel( ) routine to request delivery of a pending cancel to the current thread

· The pthread_setasynccancel( ) routine to enable and disable asynchronous cancelability

· The pthread_cancel( ) routine to request that a thread be canceled

##