Linux_ pthread 线程的取消
线程的取消(即:线程的终止)
某个线程,可以要求指定的线程终止!
方法:
1. 发送取消请求
pthread_cancel
原型:int pthread_cancel (pthread_t thread);
注意:指定的线程接收到这个"请求"后,不一定马上就终止。
取决于"被取消线程"的 “取消请求”的使能和类型。
“取消请求”的使能
pthread_setcancelstate
原型:int pthread_setcancelstate (int state, int *oldstate);
参数:state, PTHREAD_CANCEL_ENABLE 表示允许接收“取消请求” (默认状态)
PTHREAD_CANCEL_DISABLE 表示禁止接收“取消请求”
oldstate, 获取原来的取消使能状态。“取消请求”的类型
pthread_setcanceltype
原型:int pthread_setcanceltype (int type, int *oldtype);
参数: type,
1) PTHREAD_CANCEL_ASYNCHRONOUS
接受到“取消请求”后,立即取消该线程2) PTHREAD_CANCEL_DEFERRED (默认状态) 接受到“取消请求”后,直到“任意线程"中执行了以下函数之一就取消该线程。 pthread_join pthread_cond_wait pthread_cond_timeout ptrhead_testcancel sem_wait //等待信号量 sigwait //等待信号
实例
main4.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_t mythread1;
pthread_t mythread2;
void * th1_handle(void *arg)
{
int ret;
ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if (ret != 0) {
perror("pthread_setcancelstate failed!\n");
exit(1);
}
//ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
ret = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
if (ret != 0) {
perror("pthread_setcanceltype failed!\n");
exit(1);
}
while(1) {
printf("my thread...\n");
sleep(1);
}
pthread_exit(NULL);
}
void * th2_handle(void *arg)
{
sleep(3);
printf("send cancel request to th1...\n");
pthread_cancel(mythread1);
pthread_exit(NULL);
}
int main(void)
{
int ret;
ret = pthread_create(&mythread1, NULL, th1_handle, NULL);
if (ret != 0) {
printf("create thread failed!\n");
}
ret = pthread_create(&mythread2, NULL, th2_handle, NULL);
if (ret != 0) {
printf("create thread failed!\n");
}
pthread_join(mythread1, NULL);
pthread_join(mythread2, NULL);
//while(1);
return 0;
}