有没有办法链接linux';s线程TID和pthread“u t”;线程ID“;

有没有办法链接linux';s线程TID和pthread“u t”;线程ID“;,linux,pthreads,pid,Linux,Pthreads,Pid,在linux上,线程由pthread\u t或TID标识。我正在寻找这两种线程ID之间的桥梁: 给定一个pthread\u t我可以得到它的TID?没有对pthread的内部进行黑客攻击是不行的:(但我仍然在问,万一有人有干净的方法来做这件事 给定一个TID(或PID),我可以得到它的pthread\u t句柄吗 由于术语“线程id”在此上下文(以及文档中)中不明确,因此有一点背景: POSIX pthread API定义了一个pthread\u t类型,所有查询/操作线程的函数都使用p

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

  • 给定一个
    pthread\u t
    我可以得到它的
    TID
    ?没有对pthread的内部进行黑客攻击是不行的:(但我仍然在问,万一有人有干净的方法来做这件事
  • 给定一个
    TID
    (或
    PID
    ),我可以得到它的
    pthread\u t
    句柄吗

由于术语“线程id”在此上下文(以及文档中)中不明确,因此有一点背景:

  • POSIX pthread API定义了一个
    pthread\u t
    类型,所有查询/操作线程的函数都使用
    pthread\u t
    参数,我们可以获得这样的句柄,例如使用
    pthread\u self()
    。文档调用这些“线程ID”,但这里我调用它们来消除歧义,因为多个不同的
    pthread\u t
    值可能代表同一个线程,因此需要
    pthread\u equal(pthread\u t,pthread\u t)

  • 另一方面,至少在linux上,存在
    TID
    s或线程ID的概念。可以通过系统调用获得当前
    TID
    :syscall(SYS\u gettid)。
    TID
    具有一些有趣的属性,例如,对于线程来说是唯一的,并且可以与
    PID
    s进行比较,从而可以轻松识别主线程等


不幸的是,没有便携的方法可以做到这一点,因为:

实现可以选择将线程ID定义为一个结构。这比使用int允许更多的灵活性和健壮性。例如,线程ID可以包含一个序列号,允许检测“悬空ID”(已分离的线程ID的副本)。由于C语言不支持对结构类型进行比较,因此提供了pthread_equal()函数来比较线程ID

以前,
pthread\u t
没有将1对1映射到
tid

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

只是出于好奇,glibc说:

以及:


您打算如何使用
TID
?@MaximeGroushkin:更容易调试/跟踪(因为它是唯一的),在另一个主线程上执行操作,或者使用linux特定的线程函数,这些函数不是pthread.sad抽象的,但无论如何都要感谢glibc示例。反过来说,从pid/tid获取
pthread\t
有什么诀窍吗?
extern struct pthread*\uu find\u thread\u by\u id(pid\t tid)属性_hidden
,请注意该属性。另外
struct pthread*self=THREAD_self;
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);
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;