The Linux Programming Interface

(nextflipdebug5) #1
Threads: Thread Cancellation 675

printf("New thread started\n"); /* May be a cancellation point */
for (j = 1; ; j++) {
printf("Loop %d\n", j); /* May be a cancellation point */
sleep(1); /* A cancellation point */
}

/* NOTREACHED */
return NULL;
}

int
main(int argc, char *argv[])
{
pthread_t thr;
int s;
void *res;

s = pthread_create(&thr, NULL, threadFunc, NULL);
if (s != 0)
errExitEN(s, "pthread_create");

sleep(3); /* Allow new thread to run a while */

s = pthread_cancel(thr);
if (s != 0)
errExitEN(s, "pthread_cancel");

s = pthread_join(thr, &res);
if (s != 0)
errExitEN(s, "pthread_join");

if (res == PTHREAD_CANCELED)
printf("Thread was canceled\n");
else
printf("Thread was not canceled (should not happen!)\n");

exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––– threads/thread_cancel.c

32.4 Testing for Thread Cancellation


In Listing 32-1, the thread created by main() accepted the cancellation request
because it executed a function that was a cancellation point (sleep() is a cancellation
point; printf() may be one). However, suppose a thread executes a loop that con-
tains no cancellation points (e.g., a compute-bound loop). In this case, the thread
would never honor the cancellation request.
The purpose of pthread_testcancel() is simply to be a cancellation point. If a can-
cellation is pending when this function is called, then the calling thread is terminated.
Free download pdf