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

标签 c linux pthreads pid

我正在读一本关于 unix 的书。它说在 linux 中,线程有不同的 pid。并给出下面的代码来打印 pid 和线程 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)

最佳答案

在 Linux 中,从用户空间来看,线程具有相同的线程,从 View 空间来看,它们各自具有单独的 PID。

另请参阅:Linux - Threads and Process

关于c - 为什么在 linux 中使用线程打印相同的 pid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18018419/

相关文章:

c++ - Pthread 条件变量是连续轮询的替代品,是真的吗?

c - Pthread C 同步

c - 不同文件中同名的静态变量

c - 使用 strtok() 将字符串拆分为字符串不起作用

linux - 输出一个文本文件,包括用于生成它的命令

c - 使用多个线程分配内存时出现段错误

c - 尝试使用指针数组和冒泡排序编写数据排序程序,请帮忙

c - 为什么 Kernighan 和 Ritchie 包含看似不必要的类型转换?

c# - .Net 核心 API 在 linux 机器上的监控

Java 错误 (hsqldb)