【Linux系统编程】线程_01_线程基本API_03_终止进程cancel

cancel(了解)

  1. 功能:发送取消请求
  2. 原型
int pthread_cancel(pthread_t thread);
  1. 参数
    1)tid
  2. 返回值
    成功:返回0
    失败:返回非0
  3. 取决于线程的属性
    a.是否响应:取消state,pthread_setcancelstate
    b.如何响应:取消type,pthread_setcanceltype
    c.取消点:可能会陷入后时间阻塞,例:sleep,pthread_testcancel()
  4. DO
#include <func.h>

void* start_routine(void* args) {
    // 将取消状态设置为 PTHREAD_CANCEL_DISABLE
    // int oldstate;
    // pthread_sercancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);

    // &oldstate and &oldtype: 保存原来的状态,便于恢复

    // 将取消状态设置为 PTHREAD_CANCEL_ASYNCHROUS
    // int oldtype;
    // pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
    
    while (1) {
        // 设置取消点
        pthread_testcancel();
        printf("Hello World\n");
        sleep(2);
    }
}

int main(int argc, char* argv[]) {
    pthread_t tid;

    int err = pthread_create(&tid, NULL, start_routine, NULL);
    if (err) {
        error(1, err, "pthread_create");
    }

    sleep(1);

    err = pthread_cancel(tid);
    if (err) {
        error(1, err, "pthread_cancel %lu", tid);
    }

    // 等待子线程结束
    err = pthread_join(tid, NULL);
    if (err) {
        error(1, err, "pthrad_join %lu", tid);
    }

    // ps -elLf | grep "./test_cancel"

    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值