Linux_ pthread 线程的取消
2016-04-02 04:26
495 查看
线程的取消(即:线程的终止)
某个线程,可以要求指定的线程终止!
方法:
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
接受到“取消请求”后,立即取消该线程
实例
main4.c
某个线程,可以要求指定的线程终止!
方法:
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; }
相关文章推荐
- Linux _条件变量
- linux 安装Python 包
- Linux用户和用户组管理
- Linux中Shutdown命令实现定时自动关机 ---fwqlzz love is for ever
- 如何用LINUX命令格式化U盘 ---fwqlzz love is for ever
- linux kernel current宏
- linux的ACL
- Linux中搭建SVN服务器
- cmake记坑帖
- Linux中export导入环境变量的几种方式
- CentOS6.7网卡配置及常见问题(linux ip配置)
- deepin使用串口工具的使用方法
- Linux中vim编辑器莫名下方出现H的问题
- Linux系统如何创建一个新进程
- 编写Linux中sh文件执行时出现莫名字符的问题
- python在linux上的GUI无法弹出界面
- python在linux上的GUI无法弹出界面
- Installing ZFS RAID-Z on CentOS 6.6 with SSD
- linux lidb 安装
- centos-7 /usr/bin/ld: cannot find -lstdc++ 解决方法