3.6线程取消

/*
       #include <pthread.h>
       int pthread_cancel(pthread_t thread)
            功能:取消线程(让线程终止)要到某个取消点才会取消
                取消某个线程,可以终止某个线程的运行,
                但不是立马终止,而是当子线程执行到一个取消点,线程才会终止
                取消点:系统规定号的一些系统调用,我们可以粗略的理解为从用户区到内核区系统的切换
*/
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<unistd.h>
void *callback(void *arg){
    printf("child thread id : %ld\n",pthread_self());
    for(int i=0;i<5;i++){
        printf("child : %d\n",i);
    }
    return NULL;
}
int main(){

    //创建一个子线程
    pthread_t tid;

    int ret = pthread_create(&tid,NULL,callback,NULL);
    if(ret!=0){
        char *errstr=strerror(ret);
        printf("error1 : %s\n",errstr);
    }
    //取消线程
    pthread_cancel(tid);

    for(int i=0;i<5;i++){
        printf("%d\n",i);
    }

    //输出主线程和子线程的id
    printf("tid %ld,main thread id : %ld\n",tid,pthread_self());
    
    pthread_exit(NULL);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值