我在Advanced Linux Programming中遇到了一个概念。这是一个链接:参考4.5 GNU/Linux 线程实现。
我很清楚作者所说的概念,但我对他为打印线程的 processID 解释的程序感到困惑。
这是代码
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_function (void* arg)
{
fprintf (stderr, "child thread pid is %d\n", (int) getpid ());
/* Spin forever. */
while (1);
return NULL;
}
int main ()
{
pthread_t thread;
fprintf (stderr, "main thread pid is %d\n", (int) getpid ());
pthread_create (&thread, NULL, &thread_function, NULL);
/* Spin forever. */
while (1);
return 0;
}
根据作者,上述代码的输出是
% cc thread-pid.c -o thread-pid -lpthread
% ./thread-pid &
[1] 14608
main thread pid is 14608
child thread pid is 14610
我编译时得到的输出是
[1] 3106
main thread pid is 3106
child thread pid is 3106
我知道要创建一个线程,linux 在内部调用clone(大多数情况下),就像fork系统调用创建一个进程一样。唯一的区别是进程中创建的线程共享相同的进程地址空间,而父进程创建的进程复制父进程地址空间。所以,我认为在线程中打印进程 ID 会导致相同的 processID。但是,它在书中的结果不一样。
请告诉我他在说什么..?书中/我的答案是否错误..?