取消一个线程
可以请求一个线程终止,像给它发送一个信号一样.
1 请求端:
#include <pthread.h>
int pthread_cancel(pthread_t thread);
请求取消指定线程.
2 接收请求端:
#include <pthread.h>
int pthread_setcancelstate(int state, int *oldstate);
state: 线程是否接收取消请求.
| PTHREAD_CANCEL_ENABLE 允许线程接收取消请求
| PTHREAD_CANCEL_DISABLE 忽略取消请求
oldstate: 获取先前的取消状态,不关心先前状态传NULL.
#include <pthread.h>
int pthread_setcanceltype(int type, int *oldtype);
type: 如果接收到取消请求,什么时候采取行动.
| PTHREAD_CANCEL_ASYNCHRONOUS 接收到取消请求后立即采取行动.
| PTHREAD_CANCEL_DEFERRED 接收到取消请求后,等待请求端线程执行以下函数之一,再采取行动.
| (pthread_join,pthread_cond_wait, pthread_cond_timedwait, pthread_testcancel, sem_wait, sigwait)
oldtype: 获取先前的取消状态,不关心先前状态传NULL.
取消一个线程:
/*
* 取消一个线程
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg);
int main(){
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if(res != 0){
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
sleep(3);
printf("Canceling thread\n");
res = pthread_cancel(a_thread);
if(res != 0){
perror("Thread cancelation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finished\n");
res = pthread_join(a_thread, &thread_result);
if(res != 0){
perror("Thread join failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg){
int i,res;
res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if(res != 0){
perror("Thread pthread_setcancelstate failed");
exit(EXIT_FAILURE);
}
res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
if(res != 0){
perror("Thread pthread_setcanceltype failed");
exit(EXIT_FAILURE);
}
printf("thread_function is running\n");
for(i = 0; i < 10; i++){
printf("Thread is still running (%d)\n", i);
sleep(1);
}
pthread_exit(0);
} 运行结果:
$ gcc -D_REENTRANT thread7.c -o thread7 -lpthread
$ ./thread7
thread_function is running
Thread is still running (0)
Thread is still running (1)
Thread is still running (2)
Canceling thread
Waiting for thread to finished --
FROM:Linux程序设计