- 论坛徽章:
- 0
|
本帖最后由 tanggula2007 于 2010-08-19 22:35 编辑
问题是这样的:
按照书上所说(APUE(第2版) 中文版 Page:290 ),为了避免主线程退出,造成新创建的线程未能执行完,整个进程就退出,因此在主线程中使用了 sleep(1) 函数,
这一点我能明白。但是,假如现在我将 sleep(1)注释掉,执行编译出的结果时,会出现三种情况
1.主线程执行完毕,直接退出,新创建的线程未能执行完,只打印出主线程的信息;
2.主线程和新线程都执行完毕,两个线程的信息都打印出来了;
以上两种情况,我都能理解
3.除了打印出第2种情况的信息以外,新创建的线程的信息会再次打印一遍
搞不懂这是为什么?望高人出来指点指点
代码贴出来- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- pthread_t ntid;
- void
- printids(const char *s)
- {
- pid_t pid;
- pthread_t tid;
- pid = getpid();
- tid = pthread_self();
- printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
- }
- void *
- thr_fn(void *arg)
- {
- printids("new thread: ");
- return((void *)0);
- }
- int
- main(void)
- {
- int err;
- err = pthread_create(&ntid, NULL, thr_fn, NULL);
- if(err != 0)
- printf("can't create thread : %s\n", strerror(err)); //这里没有使用书上的由作者定义的出错函数
- printids("main thread:");
- // sleep(1); //故意注释了原来的代码
- exit(0);
- }
复制代码 gcc编译时需加上 "-lpthread" |
|