有没有办法链接linux的线程TID和pthread_t“线程ID”

2024-01-19

在 Linux 上,线程由pthread_t或 TID。我正在寻找这两种线程 id 之间的桥梁:

  • given a pthread_t我可以得到它吗TID ? 显然 https://stackoverflow.com/questions/558469/how-do-i-get-a-thread-id-from-an-arbitrary-pthread-t/558815#558815并非没有侵入pthread的内部结构:(但我仍然在问是否有人有一个干净的方法来做到这一点。
  • given a TID (or PID),我可以得到一个pthread_t处理好了吗?

因为术语“线程 ID”在这种情况下(以及在文档中)含糊不清,所以有一些背景知识:

  • POSIX pthread API 定义了一个pthread_t类型,所有查询/作用于线程的函数都使用pthread_t参数,我们可以得到这样的句柄,例如和pthread_self()。文档将这些称为“线程 ID”,但在这里我将它们称为句柄以消除歧义,因为多个不同的pthread_t值可能代表同一个线程,因此需要pthread_equal(pthread_t, pthread_t).

  • 另一方面,至少在linux上,有一个概念TIDs 或线程 ID。可以得到当前TID通过系统调用:syscall(SYS_gettid). The TID有一些有趣的属性,例如对于线程来说是唯一的,并且可以与PIDs,可以轻松识别主线程等。


不幸的是,没有可移植的方法来做到这一点,因为没有要求pthread_t映射到tid http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_equal.html:

实现可以选择将线程 ID 定义为结构。与使用 int 相比,这提供了额外的灵活性和鲁棒性。例如,线程 ID 可以包括允许检测“悬空 ID”(已分离的线程 ID 的副本)的序列号。由于C语言不支持结构体类型的比较,因此提供了pthread_equal()函数来比较线程ID。

从历史上看,之前NPTL https://en.wikipedia.org/wiki/Native_POSIX_Thread_Library, pthread_t没有一对一映射到tid.

您需要使用 pthreads 库实现细节来查看tid。我不建议这样做,因为这样的代码不可移植。

出于好奇,使用 glibc,pthread_t is a struct pthread * https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/pthread_kill.c;hb=HEAD#l30:

27 int
28 __pthread_kill (pthread_t threadid, int signo)
29 {
30   struct pthread *pd = (struct pthread *) threadid;
...
40   pid_t tid = atomic_forced_read (pd->tid);

And pthread is https://sourceware.org/git/?p=glibc.git;a=blob;f=nptl/descr.h;hb=HEAD#l123:

122 /* Thread descriptor data structure.  */
123 struct pthread
124 {
...
166   /* Thread ID - which is also a 'is this thread descriptor (and
167      therefore stack) used' flag.  */
168   pid_t tid;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法链接linux的线程TID和pthread_t“线程ID” 的相关文章

随机推荐