Chinaunix

标题: apue pthread_create例子的一些疑问 [打印本页]

作者: butterinsect    时间: 2011-02-23 17:32
标题: apue pthread_create例子的一些疑问
  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.
其中我有一点疑问:新线程没创建怎么就会被调用拉?
作者: lwrsmy    时间: 2011-02-23 19:08
线程创建好了 已经执行
但是pthread_create还没有返回
pthread_create()
{
  clone();//创建线程
  .....
return;
}
作者: butterinsect    时间: 2011-02-23 21:49
,懂了




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2