c - APUE 对 linux 线程的描述有误吗?

标签 c linux multithreading linux-kernel

在图11.2 APUE 2nd中,有一段代码演示了threads API的用法,如下:

#include <pthread.h>
#include <stdio.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(void)
{
        int err;

        err = pthread_create(&ntid, NULL, thr_fn, NULL);
        if (err != 0)
                return -1;

        printids("main thread: ");
        sleep(1);
        return 0;
}

书上说输出是这样的,

$./a.out
new thread: pid 6628 ...
main thread: pid 6626 ...

Pid 不同!这是因为“Linux 使用 clone() 实现线程,与 fork() 相同,因此系统将线程视为共享资源的独立进程”。

但是我测试的时候发现结果和APUE的结果不一样,是

$ ./a.out 
main thread:  pid 13301 tid 3078153920 (0xb778e6c0)
new thread:  pid 13301 tid 3078151024 (0xb778db70)

pid 是一样的!那么APUE过时了吗?但是linux确实使用clone来实现线程,在linux内核中,它们被视为不同的进程。进程ID怎么一样?

最佳答案

您的版本 APUE 很可能已经过时,因为它指的是 LinuxThreads 而不是 NPTL。

这里是 clone(2) 联机帮助页中阐明此问题的相关部分:

线程组是 Linux 2.4 中添加的一项功能,用于支持共享单个 PID 的一组线程的 POSIX 线程概念。在内部,此共享 PID 是所谓的线程组标识符 (TGID),用于线程组。从 Linux 2.4 开始,对 getpid(2) 的调用返回调用者的 TGID。

组内的线程可以通过它们的(系统范围内的)唯一线程 ID (TID) 来区分。一个新线程的 TID 作为返回给 clone() 调用者的函数结果是可用的,一个线程可以使用 gettid(2) 获得它自己的 TID。"

关于c - APUE 对 linux 线程的描述有误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9280751/

相关文章:

linux - nohup 和 & 在运行 bash 命令时有什么区别?

c++ - 符号指针与常规符号查找的 ABI 稳定性

java - 两个线程调用相同的 keyEvents 方法

c - Step Into 在 Eclipse CDT 中不起作用

c - 允许在函数定义的返回类型中定义结构有什么关系? (C)

Android Studio 和 Linux

java - 当线程被中断/杀死时,finally block 可能不会被执行吗?

multithreading - 确保 QProcess 在其父 QThread 终止时终止

从 Int 数组地址创建一个 Int 数组

c - 如何将 Yacc/Bison-Parser 包含到自己的项目中?