知识点归纳
问题和解决思路
pthread_cancel()不能杀死线程
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <pthread.h>
5 #include <string.h>
6
7 void *func(void *arg){
8 while(1);
9 return NULL;
10 }
11 int main(){
12 printf("main:pid=%d,tid=%lu
",getpid(),pthread_self());
13
14 pthread_t tid;
15 int ret = pthread_create(&tid,NULL,func,NULL);
16 if(ret != 0){
17 fprintf(stderr,"pthread_create error:%s
",strerror(ret));
18 return 1;
19 }
20
21 ret = pthread_cancel(tid);
22 if(ret != 0){
23 fprintf(stderr,"pthread_cancel error:%s
",strerror(ret));
24 return 2;
25 }
26
27 pthread_exit((void*)0);
28
29 return 0;
30 }
原因:
使用pthread_cancel()终止线程,需要线程中存在取消点。
大致是需要线程中有陷入内核的操作,才会存在取消点
如果想要用pthread_cancel()终止一个没有陷入内核操作的线程,就需要手动添加取消点
在while循环中加入,pthread_testcancel()即可用pthread_cancel()杀死该线程
7 void *func(void *arg){
8 while(1) pthread_testcancel();
9 return NULL;
10 }