0基础学会 取消一个线程pthread_cancel()(内附C语言源码)

#include <pthread.h>

int pthread_cancel(pthread_t thread);

-功能:杀死一个正在运行的线程,让线程终止。

取消线程,可以终止某个线程的运行,但是并不是立马终止,而是当子线程执行到一个取消点,线程才会终止。

取消点:系统规定好的一些系统调用,可以粗略的理解为从用户区到内核区的切换。这个位置称之为取消点。

thread:待杀死的进程id

返回值:成功:0,失败:error

用代码实现:

  1 #include <pthread.h>
  2 #include <stdio.h>
  3 #include <unistd.h>
  4 #include <stdlib.h>
  5 #include <string.h>
  6 void *callback(void *arg)
  7 {
  8         printf("child pthread:%ld\n",pthread_self());
  9         for(int i=0;i<5;++i)
 10         {
 11                 printf("child:%d\n",i+1);//这个就是取消点
 12         }
 13         return 0;
 14 }
 15 int main()
 16 {
 17         pthread_t tid;
 18         int ret=pthread_create(&tid,NULL,callback,NULL);
 19         if(ret!=0)
 20         {
 21                 printf("error info:%s\n",strerror(ret));
 22                 exit(0);
 23         }
 24 
 25         pthread_cancel(tid);//当运行到取消点后立马取消线程
 26 
 27         for(int i=0;i<5;++i)
 28         {
 29                 printf("main:%d\n",i+1);
 30         }
 31         printf("child pthread:%ld,main pthread:%ld\n",tid,pthread_self());
 32 
 33         pthread_exit(NULL);
 34 
 35         return 0;
 36 }

每次运行的结果都不一样:

第一次:

第二次: 

 

 第三次:

 可以看出每次运行的结果都不相同,说明每次运行到取消点的时间都不一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值