十一_线程3-线程的取消

本文详细介绍了线程管理的重要函数,包括pthread_cancel()用于取消线程,pthread_setcancelstate()设置线程是否允许被取消,pthread_setcanceltype()设置取消类型为异步或推迟,以及pthread_testcancel()设置取消点。

pthread_cancel() : 取消线程

pthread_setcancelstate() :设置 是否允许取消

pthread_setcanceltype(): 设置取消方式,异步 或者 推迟

pthread_testcancel(): 设置一个取消点

pthread_detach() : 线程分离


前面说到的 pthread_join() 线程收尸,是必须要等线程执行结束才能收尸,而有时候不需要目标线程执行结束 就要结束他,那么怎么收尸呢?

pthread_cancel() + pthread_join()


pthread_cancel() : 取消线程

NAME
       pthread_cancel - send a cancellation request to a thread 给一个线程发送一个取消请求。

SYNOPSIS
       #include <pthread.h>

       int pthread_cancel(pthread_t thread);//取消线程, thread :需要取消的线程ID

       Compile and link with -pthread.

为了防止已经申请的资源不能回收,需要设置取消状态,比如,如果需要取消的线程 刚刚open()了一个文件,此时取消,将会导致错过 close(),造成资源泄露。所以需要设置如下 如下状态:

取消有两种状态:

1 允许取消

1.1 异步取消
1.2 推迟取消,默认是推迟取消, 推迟到 cancel点 再响应

cancel点:POSIX定义的cancel点是指 都是可能引发阻塞的系统调用。

2 不允许取消

int pthread_setcancelstate(int state, int *oldstate); // 设置 是否允许取消

int pthread_setcanceltype(int type, int *oldtype);// 设置取消方式,异步 或者 推迟

NAME
       pthread_setcancelstate, pthread_setcanceltype - set cancelability state and type

SYNOPSIS
       #include <pthread.h>

// 设置 是否允许取消
       int pthread_setcancelstate(int state, int *oldstate); 

// 设置取消方式,异步 或者 推迟
       int pthread_setcanceltype(int type, int *oldtype);

       Compile and link with -pthread.

NAME
pthread_testcancel - 设置一个取消点

应用于 没有任何 可能引发阻塞的系统调用 的功能函数,即线程中,用于设置取消点,以便 取消该线程

SYNOPSIS
       #include <pthread.h>

// 本函数 什么都不做,就是一个取消点
       void pthread_testcancel(void);

       Compile and link with -pthread.

pthread_detach() : 线程分离

一般情况下,对于linux中的资源,我们一直遵循 :谁打开,谁关闭。谁申请,谁释放 这回原则。但是也有特殊情况,假如 创建出某个线程 就不再关心它的生死存亡,就可以分离出去,即
pthread_detach()。

注意 已经 pthread_detach()分离的线程,是不能 进行 pthread_join() 收尸的

NAME
       pthread_detach - detach a thread 分离一个线程

SYNOPSIS
       #include <pthread.h>

       int pthread_detach(pthread_t thread);

       Compile and link with -pthread.
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ma浩然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值