pthread_setcancelstate 函数(取消函数)的应用

pthread_setcancelstate 函数是 POSIX 线程(pthread)库中的一个函数,用于设置线程的取消状态。在 POSIX 线程中,线程可以被其他线程或自身请求取消,但线程可以决定自己是否对取消请求敏感。这就是通过 pthread_setcancelstate 函数来控制的。

#include <pthread.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  

void* thread_function(void* arg) 
{  
    int oldstate;  

    // 禁用取消  
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);  
  
    // 执行一些不能被取消的操作  
    // ...  

        printf("我在执行一个很重要的事情,不能取消我\n");
        sleep(5);
        printf("重要的事情-执行完毕\n");
    
    
    // 恢复取消状态  
    pthread_setcancelstate(oldstate, NULL);  
    printf("可以取消\n");

    // 现在线程可以被取消了  
    // ...  
  
    return NULL;  
}  
  
int main(int argc, char **argv)
 {  
    pthread_t thread;  // 线程 ID  
    pthread_create(&thread, NULL, thread_function, NULL);  // 创建线程  
  
    // 假设在某个点,我们决定取消线程 (主线程)
    while (1)
    {
        printf("请输入要执行的动作\n");
        printf("1、正常运行\n");
        printf("2、取消线程\n");

        int num = 0;
        scanf("%d", &num);
        while(getchar()!= '\n'); // 清空输入缓冲区

        switch (num)
        {
            case 1:
                printf("正常运行中......\n");
                break;

            case 2:
                pthread_cancel(thread); // 取消线程
                break;
        }
    }

    pthread_join(thread, NULL);  // 等待线程结束  
    return 0;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值