pthread_setcancelstate()和pthread_setcanceltype()
来源:互联网 发布:java 微信语音聊天 编辑:程序博客网 时间:2024/06/06 14:19
首先,pthread_setcancelstate()函数只是改变本线程(注意是本线程)的cancel state。所以T1进入fun()函数,执行到pthread_setcancelstate()函数时,只是改变了T1本身的cancel state,并不能改变T2的cancel state。
第二,线程执行到pthread_testcancel()函数时,并不一定会马上取消(退出)。
先描述一下取消一个线程的过程:
1) 其他线程通过调用pthread_cancel()函数,向目标线程发送取消请求(cancellation request)。
2) 取消请求发出后,根据目标线程的cancel state来决定取消请求是否会到达目标线程:
a. 如果目标线程的cancel state是PTHREAD_CANCEL_ENABLE(默认),取消请求会到达目标线程。
b. 如果目标线程的cancel state是PTHREAD_CANCEL_DISABLE,取消请求会被放入队列。直到目标线程的cancel state变为PTHREAD_CANCEL_ENABLE,取消请求才会从队列里取出,发到目标线程。
3) 取消请求到达目标线程后,根据目标线程的cancel type来决定线程何时取消:
a. 如果目标线程的cancel type是PTHREAD_CANCEL_DEFERRED(默认),目标线程并不会马上取消,而是在执行下一条cancellation point的时候才会取消。有很多系统函数都是cancellation point,详细的列表可以在Linux上用man 7 pthreads查看。除了列出来的cancellation point,pthread_testcancel()也是一个cancellation point。就是说目标线程执行到pthread_testcancel()函数的时候,如果该线程收到过取消请求,而且它的cancel type是PTHREAD_CANCEL_DEFERRED,那么这个线程就会在这个函数里取消(退出),这个函数就不再返回了,目标线程也没有了。
b. 如果目标线程的cancel type是PTHREAD_CANCEL_ASYNCHRONOUS,目标线程会立即取消(这里的“立即”只是说目标线程不用等执行到属于cancellation point的函数的时候才会取消,它会在获得调度之后立即取消,因为内核调度会有延时,所以并不能保证时间上的“立即”)。
举个例子,说明一下这些与线程取消相关的函数的用法:
void
thread_function(
void
*arg)
{
/**
* 线程准备执行一些关键工作,在这个过程中不希望被取消。
* 所以先通过pthread_setcancelstate()将本线程的cancel state
* 设为disabled。
*/
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
/* 执行关键工作 */
...
/**
* 关键工作执行完成,可以被取消。
* 通过pthread_setcancelstate()将本线程的cancel state
* 设为enabled。
*/
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
/**
* 调用pthread_testcancel()函数,检查一下在cancel state
* 为disabled状态的时候,是否有取消请求发送给本线程。
* 如果有的话就取消(退出)。
*/
pthread_testcancel();
/**
* pthread_testcancel()返回了,表明之前没有取消请求发送给本线程,
* 继续其余的工作。
* 这时候如果有取消请求发送给本线程,会在下一次执行到
* cancellation point的时候(例如sleep(), read(), write(), ...)时取消。
*/
...
/**
* 从这里开始,函数里不再包含cancellation point了。
* 如果收到取消请求,将无法取消。所以先把本线程的cancel type
* 设为asynchronous,收到取消请求将立即取消。
*/
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
/* 不包含cancellation point的代码 */
...
}
- pthread_setcancelstate()和pthread_setcanceltype()
- pthread_setcancelstate() pthread_setcanceltype() pthread_testcancel()
- pthread_testcancel函数以及pthread_setcancelstate
- 嵌入式 线程退出pthread_setcanceltype以及pthread_self以及pthread_cancel
- . 和 ->
- || 和&&
- .和::
- “?”和“!”
- #和##
- && 和 ||
- 、和
- #和##
- .//和..//
- 和
- ?和\?
- ./ 和 ../
- #和##
- #、和##
- 公钥、私钥和SSL详细说明(生动例子)
- Binder学习指南
- Java JDK的安装与配置
- java Netty远程编译代码(收藏学习)
- iOS开发之
- pthread_setcancelstate()和pthread_setcanceltype()
- POJ 2001 Shortest Prefixes
- java 通过使用wait和notify进行线程之间通信(代码)
- Linux 的字符串截取很有用。有八种方法。
- java Guava cache学习笔记
- 【面试题】剑指Offer-30-最小的第K个数
- java transient(不会序列化)、static关键字的作用
- elicapse时提示source not fonud 错误
- java 深入分析Volatile的实现原理