pthread_cancel()函数
- 头文件:#include<pthread.h>
- 原型:int pthread_cancel(pthread_t thread);
- 返回值:成功返回0;失败返回错误号
- 作用:杀死进程
注意:
- 线程杀死并不是实时的,有一定延时,需要等待线程到达某个取消点(使用了系统调用),也可用pthread_testcancel()函数设置一个取消点。
- 线程分离会自动释放资源,线程杀死需要回收线程才能释放资源
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<unistd.h>
4 #include<string.h>
5 void *th1(void *)
6 {
7 printf("th1_________\n");
8 return (void *)10;
9 }
10 void *th2(void *)
11 {
12 printf("th2_________\n");
13 pthread_exit((void *)20);
14 }
15 void *th3(void *)
16 {
17 pthread_testcancel();
18 while(1);
19 }
20 void main(void)
21 {
22 pthread_t tid1,tid2,tid3;
23 int *ret;
24 pthread_create(&tid1,NULL,th1,NULL);
25 pthread_join(tid1,(void **)&ret);
26 printf("___th1__%d__\n",(int)ret);
27
28 pthread_create(&tid2,NULL,th2,NULL);
29 pthread_join(tid2,(void **)&ret);
30 printf("___th2__%d__\n",(int)ret);
31
32 pthread_create(&tid3,NULL,th3,NULL);
33 int log;
34 log=pthread_cancel(tid3);
35 if(log==0){
36 printf("done\n");
37 }
38 log=pthread_join(tid3,NULL);
39 if(log==0){
40 printf("join done\n");
41 }
42 }