免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2681 | 回复: 4
打印 上一主题 下一主题

pthread_join,使得主程序的getchar()失效了。为什么? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-09-10 11:55 |只看该作者 |倒序浏览
10可用积分
在win平台上,如果主线程执行结束了,子线程都会强制的退出。

下面这个solaris下面的pthread例程,子线程一直在执行。我的目的是按任意键程序就退出。运行都没有问题。
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <pthread.h>
  5. pthread_key_t key;
  6. void print(){printf("%s\n",(char*)pthread_getspecific(key));}
  7. extern "C" void* t(void* arg){
  8.   pthread_setspecific(key,arg);
  9.   while(1){
  10.     print();
  11.     sleep(1);
  12.   }
  13.   return NULL;
  14. }
  15. int main(void){
  16.   pthread_t pa,pb;
  17.   pthread_key_create(&key,NULL);
  18.   pthread_create(&pa,NULL,t,(void*)"Thread a");
  19.   pthread_create(&pb,NULL,t,(void*)"Thread b");
  20. //  pthread_join(pa,NULL);
  21. //  pthread_join(pb,NULL);
  22.   getchar();
  23.   return 0;
  24. }
复制代码
但是,我加上那两行的pthread_join(把注释去掉),那么不管我键盘敲什么,都不会退出。

pthread_join究竟干了什么事情? 我的主进程已经结束了,为什么子进程还不结束?

最佳答案

查看完整内容

pthread_join()是把当前线程阻塞至目标线程结束才会继续运行,因为join的目的之一就是想得到目标线程退出状态。

论坛徽章:
0
2 [报告]
发表于 2010-09-10 11:55 |只看该作者
pthread_join()是把当前线程阻塞至目标线程结束才会继续运行,因为join的目的之一就是想得到目标线程退出状态。

论坛徽章:
0
3 [报告]
发表于 2010-09-10 12:02 |只看该作者
你在问什么?

论坛徽章:
0
4 [报告]
发表于 2010-09-10 12:10 |只看该作者
phtread_join会阻塞吧,直到他join的线程结束才会返回,手册里是这么说的:
The  pthread_join()  function shall suspend execution of the calling thread until the target thread terminates,
unless the target thread has already terminated.

论坛徽章:
0
5 [报告]
发表于 2010-09-10 12:12 |只看该作者
谢谢
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP