PTHREAD_CANCEL_DEFERRED情形下,pthread_cancel()给目标线程设置一个取消标志。目标线程在运行中的某些地方会查看自己是否存在取消请求,如果有,就立刻终止执行后继代码并退出。这些查看是否存在取消请求的地方,称之为取消点(Cancelation-point)。
下面的代码,是在suse linux中的pthread_cancel编程指南中例子的基础上修改得到:
#include <pthread.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) static void * thread_func(void *ignored_argument) { int s; pthread_t *pthr = (pthread_t *)ignored_argument; /* Disable cancellation for a while, so that we don't immediately react to a cancellation request */ s = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); if (s != 0) handle_error_en(s, "pthread_setcancelstate"); printf("thread_func(id %u (0x%x)): started; cancellation disabled\n", (unsigned int)(*pthr), (unsigned int)(*pthr)); sleep(5); printf("thread_func(id %u (0x%x)): about to enable cancellation\n", (unsigned int)(*pthr), (unsigned int)(*pthr)); s = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if (s != 0) handle_error_en(s, "pthread_setcancelstate"); /* sleep() is a cancellation point */ sleep(10); /* Should get canceled while we sleep */ /* Should never get here */ printf("thread_func(id %u (0x%x)): not canceled!\n", (unsigned int)(*pthr), (unsigned int)(*pthr)); return NULL; } int main(void) { pthread_t thr1; pthread_t thr2; void *res; int s; /* Start a thread and then send it a cancellation request */ s = pthread_create(&thr1, NULL, &thread_func, (void*)&thr1); if (s != 0) handle_error_en(s, "pthread_create 1"); s = pthread_create(&thr2, NULL, &thread_func, (void*)&thr2); if (s != 0) handle_error_en(s, "pthread_create 2"); sleep(2); /* Give thread a chance to get started */ printf("main(): sending cancellation request\n"); s = pthread_cancel(thr1); if (s != 0) handle_error_en(s, "pthread_cancel"); /* Join with thread to see what its exit status was */ s = pthread_join(thr1, &res); if (s != 0) handle_error_en(s, "pthread_join"); if (res == PTHREAD_CANCELED) printf("main(): thread 1 was canceled\n"); else printf("main(): thread 1 wasn't canceled (shouldn't happen!)\n"); s = pthread_join(thr2, &res); if (s != 0) handle_error_en(s, "pthread_join"); if (res == PTHREAD_CANCELED) printf("main(): thread 2 was canceled\n"); else printf("main(): thread 2 wasn't canceled (shouldn't happen!)\n"); exit(EXIT_SUCCESS); }