On linux a thread is identified by a pthread_t
or a TID. I'm looking for bridges between these two kinds of thread ids:
- given a
pthread_t
can I get it'sTID
? apparently not without hacking in pthread's internals :( but i'm still asking in case someone has a clean way to do it. - given a
TID
(orPID
), can I get apthread_t
handle to it ?
Because the term "thread id" is ambiguous in this context (and in the documentation), a bit of background:
The POSIX pthread API defines a
pthread_t
type, all functions that query/act on a thread use apthread_t
argument, and we can get such a handle e.g. withpthread_self()
. The documentation calls these "thread ids", but here I call them handles to disambiguate, because multiple differentpthread_t
values may represent the same thread, hence the need forpthread_equal(pthread_t, pthread_t)
.On the other hand, on linux at least, there is a concept of
TID
s or thread ids. One can get the currentTID
with a system call:syscall(SYS_gettid)
. TheTID
has a few interesting properties such as being unique to a thread, and comparable toPID
s, which allows to easily identify the main thread, etc.
Unfortunately, there is no portable way to do so because there is no requirement for
pthread_t
to map totid
:Historically, prior to NPTL,
pthread_t
did not map 1-to-1 totid
.You would need to use pthreads library implementation details to peek at
tid
. I would not recommend doing that because such code would not be portable.For the sake of curiosity only, with glibc,
pthread_t
is astruct pthread *
:And
pthread
is: