取消一个线程
2012-02-25 23:36
148 查看
有时,我们想让一个线程可以要求另一个线程终止,就像给它发送一个信号一样。线程有方法可以做到这一点,与信号处理一样,线程可以被要求终止时改变其行为。
#include <pthread.h>
int pthread_cancel(pthread_t thread);
这个函数简单易懂,提供一个线程标识符,我们就可以发生请求来取消它。但在接收到取消请求的一端,事情会稍微复杂一点,不过也不是非常复杂。线程可以用pthread_setcancelstate设置自己的取消状态。
#include <pthread.h>
int pthread_setcancelstate(int state,int *oldstate);
第一个参数的取值可以是PTHREAD_CANCEL_ENABLE,这个值允许线程接收取消请求;或者是PTHREAD_CANCEL_DISABLE,它的作用是忽律取消请求。
#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 finish...\n"); res = pthread_join(a_thread,&thread_result); if(res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } } 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); }
./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 finish
相关文章推荐
- 弄懂线程取消的一个例子
- 取消一个线程
- 如何取消一个正在运行的线程
- linux程序设计——取消一个线程(第十二章)
- 如何取消一个正在运行的线程
- 取消一个线程
- pthread_cancel,取消一个线程
- c# Task编程一个task抛出异常后怎么取消其他线程
- 如何取消一个正在运行的线程
- 关于多个异步任务线程如何取消上一个线程的问题
- 如何异步取消一个线程
- linux程序设计——取消一个线程(第十二章)
- 线程启动一个不带参数的方法
- 同时存在n个线程(n>5),需要写入或者读取一个名为test.txt的文件
- 这里实现一个基于数组的线程安全的循环队列
- 进程与线程的一个简单解释
- 树形多选框,选中/取消父节点子节点全选中/取消,选中一个子节点父节点选中,子节点全取消父节点取消
- 一个失败的案例,一个线程创建非模态对话框,主线程做其它事,对话框按钮不能响应鼠标
- 两个线程解决一个线程卡之路
- 进程与线程的一个简单解释