线程退出函数pthread_cancel() 采坑点

pthread_cancel() 时用来线程退出的,但是在使用的时候还是有一些要注意的地方。如下代码:

static void* pthread_func1(void* arg)
{
    while(1)
    {
        printf("haha\n");
        sleep(1);
    }
    return NULL;
}

static void* pthread_func2(void* arg)
{
    int a = 0;
    for( ;; )
        a++;
    return NULL;
}

int main(int argc, char const *argv[]) {
    pthread_t tid;
    pthread_create(&tid, NULL, pthread_func2, NULL);

    pthread_cancel(tid);
    pthread_join(tid, NULL);
    return 0;
}

执行pthread_func1()结果是:

duan@duan:~/repo$ g++ cancel_pthread_test.cpp -lpthread
duan@duan:~/repo$ ./a.out 
haha

执行pthread_func2()结果是无线循环不退出。

这个是因为pthread_cancel()函数不是直接使得线程退出,而是在系统调用中设置一个cancelpoint,当有系统调用函数的时候就会检查是有设置了这个cancelpoint,如果设置了那么就退出线程,相反不退出。而sleep()就属于系统调用,在使用sleep的时候系统会检查cancelpoint那么这个时候pthread_cancel()就会直接退出线程。但是在pthread_func2()函数中没有系统调用函数全是C代码,所以不会设置这个cancelpoint,故不会退出线程。

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值