linux系统编程 杀死线程

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 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值