gettid() 为两个不同的线程返回相同的值?

gettid() returning the same value for two different threads?

我有一个教授编写的程序(我对其进行了一些修改以测试内容)。据我了解,在 Linux 系统上:

  1. 用户线程无法利用多核系统,而内核线程可以。由于 pthread 可以利用多核系统,它是一个内核线程

  2. gettid returns 由内核分配的 id,并且应该是唯一的,因为线程 运行 在不同的内核上; pth_self returns进程内id

我希望看到 gettid 有 2 个不同的值,但这是我得到的:

代码:

void *count(void *arg) {
    printf("pth_self : %d gettid() : %i \n", pth_self(), gettid());
}

int main(int argc, char **argv) {
    pth_init();
    pth_t t1, t2;
    t1 = pth_spawn(PTH_ATTR_DEFAULT, count, &a);
    t2 = pth_spawn(PTH_ATTR_DEFAULT, count, &a);
    pth_join(t1,NULL);
    pth_join(t2,NULL);
    return 0;
}

输出:

pth_self : 23023312 gettid() : 45868 
pth_self : 23090368 gettid() : 45868

为什么 gettid 为 2 个线程返回相同的东西?如果这很重要,我还会收到关于某种“gettid 的隐式声明”的警告。

谢谢

您正在混合pthread and pth

首先使用clonefutex系统调用(参见here)。线程为内核所知,可以利用SMP系统。

第二个does all in user space:内核只看到一个线程,所以gettid()将return所有'thread'中的相同值。

您可能会问“如果 pth 不创建真正的线程,为什么存在?”

答案是here:

Pth increases the responsiveness and concurrency of an event-driven application, but NOT the concurrency of number-crunching applications.


要为不同的线程设置不同的 tid 值,您必须将代码更改为:

/* compile with -pthread */
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <pthread.h>

/* see NOTES of https://linux.die.net/man/2/gettid for explanation */
#define gettid() syscall(SYS_gettid)

void *count(void *arg) {
    printf("pthread_self : %ld gettid() : %li \n", pthread_self(), gettid());
    return NULL;
}

int main(int argc, char **argv) {
    pthread_t t1, t2;

    pthread_create(&t1, NULL, count, NULL);
    pthread_create(&t2, NULL, count, NULL);

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    return 0;
}

输出:

pth_self : 140492392244992 gettid() : 4422 
pth_self : 140492383852288 gettid() : 4423 

Try it online