Linux学习之系统编程篇:杀死 / 取消线程

函数:

int pthread_cancel(pthread_t thread);//参数:线程 ID

注意:并不是调用了 pthread_cancel,就一定能杀死进程,
必须死在“取消点”上,就是必须作一次系统调用,在不知道函数体中是否有取消点的情况下,也可以手动添加 pthread_testcancel();
举例:

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
void * func (void *arg) {
 while(1){
 // printf("I am a thread,tid=%lu\n", pthread_self() ); //获得子线程ID
 // sleep(1);
 pthread_testcancel(); // 如果while内语句全部注释后,就必须自己设置取消点
 }
 return NULL; }
int main()
{
 pthread_t tid;
 pthread_create(&tid, NULL, func, NULL); //创建子线程
 printf("I am main thread, will kill %lu after 3s\n", tid);
 sleep(3); //防止子线程马上被杀死
 pthread_cancel(tid); //杀死线程
 int ret = pthread_join(tid, NULL); //回收子进程资源
 if(ret > 0){
 printf("ret = %d, msg=%s\n",ret, strerror(ret)); //回收失败,输出错误号,打印错误信息
 }
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值