【问题标题】:why use thread in linux print same pid?为什么在linux中使用线程打印相同的pid?
【发布时间】: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 特定的部分可能不太实际。

标签: c linux pthreads pid


【解决方案1】:

在 Linux 中,从用户空间来看,线程具有相同的线程,从视图空间来看,它们每个都有一个单独的 PID。

另请参阅:Linux - Threads and Process

【讨论】:

    【解决方案2】:

    线程是同一个进程中的一个概念,它们总是有相同的pid。只有当你分叉一个进程时,pid才会改变;在这种情况下,子进程将具有与父进程不同的 pid。

    【讨论】:

    • 但是书上说:linux use clone to create new thread .这意味着不同的pid。
    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多