[转]linux下多线程之pthread_detach(pthread_self())
来源:互联网 发布:正版黑界扣字软件下载 编辑:程序博客网 时间:2024/06/03 21:57
创建一个线程默认的状态是joinable, 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码),所以创建线程者应该pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源(类似于wait,waitpid)
但是调用pthread_join(pthread_id)后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此,比如在Web服务器中当主线程为每个新来的链接创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的链接),这时可以在子线程中加入代码
pthread_detach(pthread_self())
或者父线程调用
pthread_detach(thread_id)(非阻塞,可立即返回)
这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。
pthread_detach(pthread_self())
linux线程执行和windows不同,pthread有两种状态joinable状态和unjoinable状态,
如果线程是joinable状态,当线程函数自己返回退出时或pthread_exit时都不会释放线程所占用堆栈和线程描述符(总计8K多)。只有当你调用了pthread_join之后这些资源才会被释放。
若是unjoinable状态的线程,这些资源在线程函数退出时或pthread_exit时自动会被释放。
unjoinable属性可以在pthread_create时指定,或在线程创建后在线程中pthread_detach自己, 如:pthread_detach(pthread_self()),将状态改为unjoinable状态,确保资源的释放。或者将线程置为 joinable,然后适时调用pthread_join.
其实简单的说就是在线程函数头加上 pthread_detach(pthread_self())的话,线程状态改变,在函数尾部直接 pthread_exit线程就会自动退出。省去了给线程擦屁股的麻烦
eg:
pthread_t tid;
int status = pthread_create(&tid, NULL, ThreadFunc, NULL);
if(status != 0)
{
perror("pthread_create error");
}
pthread_detach(tid);
0 0
- [转]linux下多线程之pthread_detach(pthread_self())
- linux下多线程 之 pthread_detach(pthread_self())
- linux下多线程 之 pthread_detach(pthread_self())
- linux下多线程 之 pthread_detach(pthread_self())
- linux下多线程 之 pthread_detach(pthread_self())
- linux下多线程 之 pthread_detach(pthread_self())
- linux下多线程 之 pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- linux下多线程之pthread_detach(pthread_self())
- pthread_detach(pthread_self())
- 多线程函数系列pthread_create(), pthread_join(), pthread_self(),pthread_exit(), pthread_detach()实例详解
- mysql insert一条记录(事务提交之前)怎样返回创建记录的主键id,last_insert_id(),selectkey && <select> 标签属性
- Mysql
- 快速排序(C语言实现)
- Lintcode 克隆二叉树
- java 插入排序
- [转]linux下多线程之pthread_detach(pthread_self())
- 线段树?线段树!
- Gitlab安装和使用
- mysql查询事务和锁
- unit9练习题
- InputStream 、 InputStreamReader 、 BufferedReader区别
- 数据库基础知识
- 第九单元练习题
- Linux--shell脚本执行方法总结