【问题标题】:gettid() returning the same value for two different threads?gettid() 为两个不同的线程返回相同的值?
【发布时间】:2021-01-10 06:10:54
【问题描述】:

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

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

  2. gettid 返回内核分配的 id 并且应该是唯一的,因为线程运行在不同的内核上; pth_self返回进程内的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”的警告。

谢谢

【问题讨论】:

  • 添加#define _GNU_SOURCE #include <unistd.h> #include <sys/types.h> 以避免警告。 ref
  • %i 对于gettid() 可能不正确。建议printf("pth_self : %lld gettid() : %lli\n", (long long) pth_self(), (long long) gettid()); 避免类型不匹配问题。
  • 第一个 count 是否在第二个 pth_spawn 之前终止,然后再使用旧的 tid?
  • 您的程序充满了对非标准函数的调用和对非标准数据类型的使用。那么,除非通过猜测,否则我们如何才能了解程序的行为尚不清楚。
  • 然而,问题散文中似乎至少表达了一种误解。在gettid() 返回的线程 ID 的意义上,Pthreads 不是内核线程。 pthread_t 对象存在于用户空间中,pthreads 函数是用户函数,而不是内核函数。但是他们使用内核线程来实现他们的行为。

标签: c linux multithreading pthreads


【解决方案1】:

您正在混合pthreadpth

首先使用clonefutex系统调用(见here)。线程是内核已知的,可以利用SMP系统。

第二个在用户空间做所有事情:内核只看到一个线程,所以gettid() 将在所有“线程”中返回相同的值。

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

答案是here

Pth 提高了事件驱动应用程序的响应能力和并发性,但不会提高数字运算应用程序的并发性。


要为不同的线程设置不同的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2015-09-15
    • 2015-09-28
    相关资源
    最近更新 更多