===========How I came to this question=============
I attempted to find some information about certain threads in runtime by printing out their thread id and looking them up in the output of ps -l -T <PID>
. Obviously this did not work because pthread_self() and gettid() return different values. I wonder if there is a way to find the right thread entry in ps command output with the p_thread id.
stdout of the program who prints out pthread id
~/a.out
current thread id is current thread id is 139911304836672
ps output
ps -l -T 80353
F S UID PID SPID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S - 80353 80353 80072 0 80 0 - 3561 futex_ pts/4 0:00 ./a.out
1 S - 80353 80354 80072 0 80 0 - 3561 hrtime pts/4 0:00 ./a.out
CodePudding user response:
Per the POSIX standard, pthread_t
is an opaque type that is only used for referencing threads using POSIX thread API. Outside of that API the value of that type does not convey any meaning if you wish to remain compliant to the standard and write portable code. Please refer to the pthread_self(3)
manual page.
If you read the source code for your POSIX thread library of choice (which probably is NPTL [Native POSIX Threads Library]), you possibly could find a way to find the kernel thread id (as returned by gettid(2)
) but relying on that would tie your code to that POSIX thread library implementation and make your code fragile for any future library change.
If you really need to have the association, for which I see reasons for, then I believe the best you can do is to keep track of the correspondence by yourself (in thread-safe manner). Then, of course your code is Linux-specific, just like gettid(2)
and the concept of thread id are. But at least you would use documented APIs correct way without any outside assumptions, so the code would keep working as long as both POSIX thread API and gettid(2)
would still exist (and the specifics how you would use the thread id would still work the same way). By relying on documented APIs, you would noticed the breakage much easier.