【发布时间】:2013-08-02 13:43:03
【问题描述】:
我正在读一本关于 unix 的书。它说在 linux 中,线程有不同的 pid。并给出下面的代码来打印 pid 和 thread id。我使用 SUSE 和 gcc。但是,我得到相同的 pid。谁能告诉我为什么?谢谢。
#include "pthread.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()
{
int err;
err = pthread_create(&ntid,NULL,thr_fn,strerror(err));
if(err != 0)
err_quit("can't create new thread :%s\n",strerror(err));
printids("main thread :");
sleep(1);
exit(0);
}
但是,我明白了:
main thread : pid = 2945 tid = 3075803392 (0xb7550900)
new thread : pid = 2945 tid = 3075799872 (0xb754fb40)
【问题讨论】:
-
这本书肯定有错误或者你没看清楚。
-
你可以在这个问题的答案中找到一个很好的解释:stackoverflow.com/questions/9305992/linux-threads-and-process
-
@LostBoy 谢谢,非常有用
-
Linux 内部的线程实现发生了变化(从 X.Leroy 的原始线程到今天的 NPTL),并且这些变化与内核变化相互作用。
-
是的,这是一本旧书,但对于一般的 Posix 部分来说非常好。 Linux 特定的部分可能不太实际。