免费注册 查看新帖 |

Chinaunix

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

apue pthread_create例子的一些疑问 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-02-23 17:32 |只看该作者 |倒序浏览
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <stdlib.h>


  5. pthread_t ntid;

  6. void printids(const char *s)
  7. {
  8.         pid_t        pid;
  9.         pthread_t tid;

  10.         pid = getpid();
  11.         tid = pthread_self();
  12.         printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
  13.                         (unsigned int)tid, (unsigned int)tid);

  14. }

  15. void *thr_fn(void *arg)
  16. {
  17.         printids("new thread:");
  18.         return ((void *)0);
  19. }

  20. int main()
  21. {
  22.         int err;
  23.         err = pthread_create(&ntid, NULL, thr_fn, NULL);
  24.         if(err!=0)
  25.                 perror("can not create thread");
  26.         printids("main thread:");
  27.         sleep(1);
  28.         exit(0);

  29. }
复制代码
在apue中文版11章290页中上面的例子
书上说:在本例中,主线程吧新线程ID存放在ntid中,但是新建的线程并不能安全使用它,如果新线程在主线程
调用pthread_create返回之前就运行了
,那么新线程看到的是未经初始化的ntid的内容,这个内容不是正确的ID.
其中我有一点疑问:新线程没创建怎么就会被调用拉?

论坛徽章:
0
2 [报告]
发表于 2011-02-23 19:08 |只看该作者
线程创建好了 已经执行
但是pthread_create还没有返回
pthread_create()
{
  clone();//创建线程
  .....
return;
}

论坛徽章:
0
3 [报告]
发表于 2011-02-23 21:49 |只看该作者
,懂了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP