【问题标题】:Is there a way to link a linux's thread TID and a pthread_t "thread ID"有没有办法链接 linux 的线程 TID 和 pthread_t “线程 ID”
【发布时间】:2017-05-21 13:20:49
【问题描述】:

在 linux 上,线程由 pthread_t 或 TID 标识。我正在寻找这两种线程 ID 之间的桥梁:

  • 给定一个pthread_t 我可以得到它是TID 吗? apparently 并非没有破解 pthread 的内部结构 :( 但我仍然在问是否有人有干净的方法来做到这一点。
  • 给定一个TID(或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 的概念。可以通过系统调用获得当前的TIDsyscall(SYS_gettid)TID 有一些有趣的属性,例如线程独有,与PIDs 相当,可以轻松识别主线程等。

【问题讨论】:

  • 你打算用TID做什么?
  • @MaximEgorushkin:更容易调试/跟踪(因为它是独一无二的),在另一个主线程上执行操作,或者使用 pthread 未抽象的 linux 特定线程函数。

标签: linux pthreads pid


【解决方案1】:

不幸的是,没有可移植的方式这样做,因为there is no requirement for pthread_t to map to tid

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

从历史上看,在NPTL 之前,pthread_t 没有一对一映射到tid

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

出于好奇,使用 glibc,pthread_t is a struct pthread *

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);

还有pthread is:

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;

【讨论】:

  • 悲伤,但无论如何感谢 glibc 示例。反过来呢,有没有从 pid/tid 获取 pthread_t 的技巧?
  • extern struct pthread *__find_thread_by_id (pid_t tid) attribute_hidden,注意属性。还有struct pthread *self = THREAD_SELF;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
相关资源
最近更新 更多