Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map pthread_t to pid (on Linux)

Is there a sane way to map a pthread_t value (as returned from pthread_create() or std::thread::native_hanle() ) to pid(tid) in Linux? Before someone gets duplicate-happy, this is not about finding thread's own pid (which can be done with gettid()).

The insane way would be to somehow compel a thread to call gettid() and pass along the result, but that's way too much trouble.

One of the possible applications I have in mind is to reconcile threads created within program (where pthread_t is available) with output provided by ps -T.

like image 662
SergeyA Avatar asked Dec 14 '17 15:12

SergeyA


1 Answers

One (convoluted, non-portable, Linux-specific, lightly destructive) method of mapping pthread_t to tid without looking into struct pthread is as follows:

  1. Use pthread_setname_np to set a thread name to something unique.
  2. Iterate over subdirectories of /proc/self/task and read a line from a file named comm in each of those.
  3. If the line equals to the unique string just used, extract tid from the last component of the subdirectory name. This is your answer.

The thread name is not used by the OS for anything, so it should be safe to change it. Nevertheless you probably want to set it back to the value it had originally (use pthread_getname_np to obtain it).

like image 169
n. 1.8e9-where's-my-share m. Avatar answered Oct 07 '22 06:10

n. 1.8e9-where's-my-share m.