3.6线程取消

本文介绍了pthread_cancel函数在C语言多线程编程中的使用,它用于取消指定线程。线程并不会立即终止,而是在执行到一个取消点时才结束。取消点通常发生在系统调用处,即从用户空间到内核空间的转换。示例代码展示了如何创建并取消一个线程,以及如何在主线程和子线程中打印ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
       #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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值