int pthraed_cancel(pthread_t thread);成功返回0;失败返回错误号;
注意:线程的取消并不是实时的,而有一定的延时。需要等待线程到达某个取消点(检查点)。
系统调用(进入内核)算作一个取消点。
man 7 threads可以查看取消点
函数pthread_testcancel()可以自己设置取消点
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<pthread.h>
void* func1(void* arg)
{
printf("thread 1 return\n");
return (void*)111;
}
void* func2(void* arg)
{
printf("thread 2 exit\n");
pthread_exit((void*)222);
}
void* func3(void* arg)
{
while(1)//如果没有取消点(此函数中有系统调用),线程不会被取消,永远循环
{
printf("thread:I will be killed in 3 seconds\n");
sleep(1);
//pthread_testcancel();//自己设置取消点
}
return (void*)666;
}
int main(void)
{
pthread_t tid;
void* tret=NULL;
pthread_create(&tid,NULL,func1,NULL);
pthread_join(tid,&tret);
printf("thread 1 exit code = %d\n",(int)tret);
pthread_create(&tid,NULL,func2,NULL);
pthread_join(tid,&tret);
printf("thread 2 exit code = %d\n",(int)tret);
pthread_create(&tid,NULL,func3,NULL);
sleep(3);
pthread_cancel(tid);
pthread_join(tid,&tret);//回收已经取消的线程会返回-1
printf("thread 1 exit code = %d\n",(int)tret);
return 0;
}
结果如下