[英]gettid() returning the same value for two different threads?
我有一個由我的教授編寫的程序(我對其進行了一些修改以進行測試)。 據我了解,在 Linux 系統上:
用戶線程無法利用多核系統,而 kernel 線程可以。 由於 pthread 可以利用多核系統,因此它是 kernel 線程
gettid
返回由 kernel 分配的 id,並且應該是唯一的,因為線程在不同的內核上運行; pth_self
返回進程內的 id
我希望看到 2 個不同的gettid
值,但這就是我得到的:
代碼:
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;
}
output:
pth_self : 23023312 gettid() : 45868
pth_self : 23090368 gettid() : 45868
為什么 gettid 為 2 個線程返回相同的東西? 如果這很重要,我還會收到有關某種“隱式聲明 gettid”的警告。
謝謝
第一次使用clone
和futex
系統調用(見這里)。 線程是內核已知的,可以從 SMP 系統中獲利。
第二個在用戶空間中完成所有工作:內核只看到一個線程,因此gettid()
將在所有“線程”中返回相同的值。
你可能會問“如果 pth 不創建真正的線程,為什么它存在?”
答案在這里:
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
你有一個溢出錯誤,使結果毫無意義。
您的代碼帶有 int 溢出: printf("pth_self: %d gettid(): %i \n", pth_self(), gettid());
更正: printf("pth_self: %ld gettid(): %ld \n", (long)pth_self(), (long)gettid());
使用通常的默認 linux 編譯,pthread_self() 為 8 字節,int 為 4,pthread_t 為 8 字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.