Dangers exist in performing cancellations. Most deal with properly restoring invariants and freeing shared resources. A thread that is cancelled without care might leave a mutex in a locked state, leading to a deadlock. Or a cancelled thread might leave a region of allocated memory with no way to identify the memory and therefore unable to free the memory.
The standard C library specifies a cancellation interface that permits or forbids cancellation programmatically. The library defines cancellation points that are the set of points at which cancellation can occur. The library also allows the scope of cancellation handlers to be defined so that the handlers are sure to operate when and where intended. The cancellation handlers provide clean up services to restore resources and state to a condition that is consistent with the point of origin.
Placement of cancellation points and the effects of cancellation handlers must be based on an understanding of the application. A mutex is explicitly not a cancellation point and should be held only for the minimal essential time.
Limit regions of asynchronous cancellation to sequences with no external dependencies that could result in dangling resources or unresolved state conditions. Take care to restore cancellation state when returning from some alternate, nested cancellation state. The interface provides features to facilitate restoration: pthread_setcancelstate(3C) preserves the current cancel state in a referenced variable, pthread_setcanceltype(3C) preserves the current cancel type in the same way.
Cancellations can occur under three different circumstances:
At various points in the execution sequence as defined by the standard
At a call to pthread_testcancel()
By default, cancellation can occur only at well-defined points as defined by the POSIX standard.
In all cases, take care that resources and state are restored to a condition consistent with the point of origin.