- 论坛徽章:
- 0
|
apue2中11章第一个例题,具体代码如下- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- pthread_t ntid;
- void
- err_sys(const char *s)
- {
- printf("%s\n", s);
- exit(1);
- }
- 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)
- err_sys("pthread_create error\n");
- printids("main thread:");
- sleep(1);
- exit(0);
- }
复制代码 编译
gcc -Wall test.c -lpthread
./a.out (执行结果如下)
new thread: pid 30381 tid 3085904784 (0xb7ef2b90)
main thread: pid 30381 tid 3085907648 (0xb7ef36c0)
疑问:
观察程序执行结果,与apue2上面所描述的Linux下执行结果有两点差别:
o 这里两个线程的pid相同(说明是同一个进程)
而书中所叙述的是:Linux使用clone系统调用来实现pthread_create,clone用于创建
子进程。按书所说,主线程和新线程的pid应该不同(书上的结果确实是不同pid)。
这是否说明2.6内核对线程实现机制有了改变?(书上的结果是在2.4内核环境下的)
o Linux里pthread_t实现为unsigned long int,但这里打印出来的线程ID值看起来十六
进制的表示更有意义些,这是为何? |
|