为什么在linux中使用线程打印相同的pid?

时间:2013-08-02 13:43:03

标签: c linux pthreads pid

我正在读一本关于unix的书。在linux中说,线程有不同的pid。并给出下面的代码来打印pid和线程ID。我使用SUSE和gcc.However,我得到了同样的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)

2 个答案:

答案 0 :(得分:2)

在Linux线程中,当从用户空间查看时,它们具有相同的线程,从视图空间中它们各自具有单独的PID。

另请参阅:Linux - Threads and Process

答案 1 :(得分:0)

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