pthread_cancel ()-取消线程
标准
| 标准/扩展 | C 或 C++ | 依赖关系 |
|---|---|---|
POSIX.4a
单一 UNIX 规范版本 3 |
两个 | POSIX(ON)
|
格式
#define _OPEN_THREADS
#include <pthread.h>
int pthread_cancel(pthread_t thread); SUSV3:
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_cancel(pthread_t thread);一般描述
请求取消线程。 要取消的线程控制何时通过可取消状态和类型来处理此取消请求。
可取消状态可以是:
- PTHREAD_INTR_DISABLE
- 无法取消线程。
- PTHREAD_INTR_ENABLE
- 可以取消该线程,但它受类型限制。
可取消类型可以是:
- PTHREAD_INTR_CONTROLLED
- 可以取消线程,但只能在特定执行点:
- 等待条件变量时,它是 pthread_cond_wait () 或 pthread_cond_timedwait ()
- 当等待另一个线程 (即 pthread_join ()) 的结束时
- 在等待异步信号时,它是 sigwait ()
- 专门针对取消请求 (即 pthread_testintr ()) 进行测试
- 由于 POSIX 函数或下列其中一个 C 标准函数而暂挂时: close () , fcntl () , open () pause () , read () ,tc漏 () , tcsetattr () , sigsuspend () , sigwait () , sleep () , wait () 或 write ()
- PTHREAD_INTR_异步
- 可以随时取消线程。
加入已取消线程的线程会返回 -1 状态。 有关更多信息,请参阅 pthread_join ()-等待线程结束。
pthread_t 是用于唯一标识线程的数据类型。 它由 pthread_create () 返回,并由需要线程标识的函数调用中的应用程序使用。
注: 互斥等待中的线程不会被信号中断,因此不会被取消。
C++的特殊行为: 当取消线程时,将运行堆栈上自动对象的析构器。 解开堆栈,以相反顺序运行析构函数。
SUSv3 的特殊行为: Single UNIX Standard , Version 3 定义可取消状态和类型的新符号。 这些符号等同于上述符号,必须在 SUSv3 名称空间中进行编译时使用。 状态的符号为 PTHREAD_CANCEL_ENABLE 和 PTHREAD_CANCEL_DISABLE。 类型的符号为 PTHREAD_CANCEL_DEFERRED 和PTHREAD_CANCEL_异步。
返回值
如果成功, pthread_cancel () 将返回 0。 Success 指示已发出 pthread_cancel () 请求。 要取消的线程可能由于其中断状态而仍然执行。
如果不成功,pthread_create() 返回 -1 ,并将 errno 设为下列值之一:
- 错误代码
- 描述
- EINVAL
- 指定的线程无效。
- ESRCH
- 指定的线程未引用当前存在的线程。
单一 UNIX 规范版本 3 的特殊行为:
如果失败, pthread_cancel () 将返回错误号以指示错误。
示例
CELEBP14
/* CELEBP14 */
#define _OPEN_THREADS
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int thstatus;
void * thread(void *arg)
{
puts("thread has started. now sleeping");
while (1)
sleep(1);
}
main(int argc, char *argv[])
{
pthread_t thid;
void *status;
if ( pthread_create(&thid, NULL, thread, NULL) != 0) {
perror("pthread_create failed");
exit(2);
}
if ( pthread_cancel(thid) == -1 ) {
perror("pthread_cancel failed");
exit(3);
}
if ( pthread_join(thid, &status)== -1 ) {
perror("pthread_join failed");
exit(4);
}
if ( status == (int *)-1 )
puts("thread was cancelled");
else
puts("thread was not cancelled");
exit(0);
}
输出:
thread has started. now sleeping
thread was canceled相关信息
- pthread.h -线程接口
- pthread_cond_timedwait () , pthread_cond_timedwait64()-等待条件变量
- pthread_cond_wait ()-等待条件变量
- pthread_exit ()-退出线程
- pthread_join ()-等待线程结束
- pthread_setcancelstate ()-设置线程可取消状态格式
- pthread_setcanceltype ()-设置线程可取消类型格式
- pthread_setintr ()-设置线程可取消状态
- pthread_setintrtype ()-设置线程可取消类型
- pthread_testcancel ()-建立取消点
- pthread_testintr ()-建立可取消点