在任何一个时间点上,线程是可结合的(joinable),或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死;在被其他线程回收之前,它的存储器资源(如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。

默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该要么被显示地回收,即调用pthread_join;要么通过调用pthread_detach函数被分离。如果一个可结合线程结束运⾏行但没有被join,则它的状态类似于进程中的Zombie Process, 即还有一部分资源没有被回收,所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。 由于调用pthread_join后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。例如,在Web服务器中当主线程为每个新来的连接请求创建一个子线程进 行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来 的连接请求), 这时可以在子线程中加入代码:

pthread_detach(pthread_self());

或者父线程调用时加入:

pthread_detach(thread_id)

这将该子线程的状态设置为分离的(detached),如此一来,该线程运⾏行结束后会自动释 放所有资源。

代码示例:

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h> void* pthread_running(void *_val)
{
pthread_detach(pthread_self());
printf("%s\n", (char*)_val);
return NULL;
} int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, pthread_running, "main thread is running"); if(ret != 0)
{
printf("create thread error! info is:%s\n", strerror(ret));
return ret;
} int temp = 0;
sleep(1);
if(0 == pthread_join(tid, NULL))
{
printf("pthread wait success!\n");
temp = 0;
}
else
{
printf("pthread wait failed!\n");
temp = 1;
} return temp;
}

运行结果:

最新文章

  1. winfrom 限制文本框小数点后两位
  2. PHP的学习--cookie和session
  3. CentOS 6.3下配置LVM(逻辑卷管理)
  4. 2.2 顺序容器-list
  5. TFS任务更新
  6. Bubble Sort_树状数组
  7. Selenium Grid 运行报错 Exception thrown in Navigator.Start first time -&gt;Error forwarding the new session Empty pool of VM for setup Capabilities
  8. 为自己的Android应用添加广告
  9. 单调队列-hdu-4193-Non-negative Partial Sums
  10. windows上编译zlib-1.2.8
  11. Linux记录-shell获取hdfs表查询mysql
  12. kafka TimeoutException 超时问题解决
  13. sqlserver把数据导入mysql
  14. 怎样从外网访问内网Jboss?
  15. ES6 Symbol的应用场景
  16. wepy中页面的跳转
  17. Linux mysql 添加远程连接
  18. API图片路径和超链接语义化转换
  19. 【BZOJ】1711: [Usaco2007 Open]Dining吃饭
  20. [005] unique_sub_string

热门文章

  1. Intellij Idea notes
  2. HttpClient详解
  3. php从数组中取出一段 之 array_slice
  4. Java程序设计8——抽象类、接口与内部类
  5. UI7Kit
  6. 马婕 2014MBA专硕考试报刊选读 5 朱令案悬而未决引起全社会的关注(转)
  7. SDWebImage从缓存中获取图片
  8. After Upgrade To Release 12.1.3 Users Receive &quot;Function Not Available To This Responsibility&quot; Error While Selecting Sub Menus Under Diagnostics (Doc ID 1200743.1)
  9. jsp+mysql的字符过滤器
  10. (zxing.net)一维码UPC A的简介、实现与解码