How to name a thread in Linux?

28,294

Solution 1

Posix Threads?

This evidently won't compile, but it will give you an idea of where to go hunting. I'm not even sure its the right PR_ command, but i think it is. It's been a while...

  #include <sys/prctl.h>
  prctl(PR_SET_NAME,"<null> terminated string",0,0,0)

Solution 2

If you are using a library like ACE the Thread has a way to specify the thread name when creating a new thread.

BSD Unix has also a pthread_set_name_np call.

Otherwise you can use prctl as mentioned by Fusspawn.

Share:
28,294
Marbal
Author by

Marbal

Updated on July 09, 2022

Comments

  • Marbal
    Marbal almost 2 years

    I have a multithreaded Linux application written in C/C++. I have chosen names for my threads. To aid debugging, I would like these names to be visible in GDB, "top", etc. Is this possible, and if so how?

    (There are plenty of reasons to know the thread name. Right now I want to know which thread is taking up 50% CPU (as reported by 'top'). And when debugging I often need to switch to a different thread - currently I have to do "thread apply all bt" then look through pages of backtrace output to find the right thread).

    The Windows solution is here; what's the Linux one?

  • Marbal
    Marbal about 15 years
    That worked, thanks! The documentation says PR_SET_NAME sets the process name; but that documentation is wrong - it does actually set the thread name. Now "top" and "ps -L" show the thread name.
  • Fusspawn
    Fusspawn about 15 years
    Glad it worked, I wasnt sure if it was even the right Constant for it, :)
  • Marbal
    Marbal almost 15 years
    Further investigation shows that busybox's "top" and "ps" don't report thread names. You need the full versions from the "procps" package.
  • Sam Liao
    Sam Liao about 13 years
    you can force "ps" to show that name with the c switch (ps Hcx for example).
  • Nemo
    Nemo over 12 years
    On Linux it's called pthread_setname_np and it was added in glibc 2.11.2.
  • Mikhail T.
    Mikhail T. over 11 years
    This is, probably, the most-detailed answer on the subject.
  • Hi-Angel
    Hi-Angel about 9 years
    @arsane not the busybox's one. Busybox tools are very limited, sometimes have a different args. And e.g. its free just give wrong results.