Operating SystemWindowsMCA

• Deferred cancellation − The target thread checks periodically whether it should terminate, allowing it an opportunity to terminate itself in an orderly fashion.

## Example

pthread t tid;
…
pthread cancel(tid);

Invoking pthread cancel() indicates only a request to cancel the target thread, however; actual cancellation depends on how the target thread is set up to handle the request. Pthreads supports three cancellation modes. Each mode is defined as a state and a type, as illustrated in the table below. Its cancellation state and type may be set by a thread using an API.

ModeStateType
OffDisabled-
DeferredEnabledDeferred
AsynchronousEnabledAsynchronous

As the table illustrates, Pthreads allows threads to disable or enable cancellation. Obviously, a thread cannot be canceled if cancellation is disabled. However, cancellation requests remain pending, so the thread can later enable cancellation and respond to the request. The default cancellation type is deferred cancellation. Here, cancellation occurs only when a thread reaches a cancellation point. One technique for establishing a cancellation point is to invoke the pthread testcancel() function. A function known as a cleanup handler is invoked, if a cancellation request is found to be pending. Any resources a thread may have acquired is allowed by this function to be released before the thread is terminated. The following code illustrates how a thread may respond to a cancellation request using deferred cancellation −

while (1){
/* do some work for a while */
/* ... */
/* check if there is a cancellation request */
}