一个线程可以对另一个线程提出取消申请,即线程被动终止的一种情况。向某个线程提出取消申请的接口:
#include <pthread.h> int pthread_cancel(pthread_t thread);
如果一个线程因响应pthread_cancel而终止的,那么连接该线程时,将得到PTHREAD_CANCELED返回值。
向线程提出取消申请,与线程真正发生终止之间,是异步的。即向线程发出取消申请,被申请线程不一定会马上终止,而是等到某个可以发生终止的时机了才终止。可以发生终止的时机,是指当线程调用某些函数时,会响应取消请求,这些函数也称为线程的取消点。 常见的线程取消点有:

实例:
/*
*thread_cancel.c
*/
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>
#define handle_error_en(en, msg) \
do {errno = en; perror(msg); exit(EXIT_FAILURE) ;} while(0)
static void *thread_routine(void *arg)
{
int j;
printf("New thread started\n"); //这里又可能是一个线程取消点
for (j = 1; ; j++)
{
printf("Loop %d\n", j); //这里也可能是一个线程取消点
sleep(1); //这里也可能是一个线程取消点
}
//程序执行流程时无法到达这里
return NULL;
}
int main()
{
pthread_t thr;
int s;
void *res;
s = pthread_create(&thr, NULL, thread_routine, NULL);
if (0 != s)
{
handle_error_en(s, "pthread_create");
}
sleep(3);
s = pthread_cancel(thr);
if (0 != s)
{
handle_error_en(s, "pthread_cancel");
}
//等待线程退出
s = pthread_join(thr, &res);
if (0 != s)
{
handle_error_en(s, "pthread_join");
}
//判断新线程终止是否是相应取消而终止的
if (res == PTHREAD_CANCELED)
{
printf("Thread was canceled\n");
}
else
{
printf("Thread was not canceled (should not happen!)\nA;");
}
return 0;
}
运行结果:
