c++ - pthread_setname_np - unix thread name

How to name a thread in Linux? (2)

This question already has an answer here:

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?

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.

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)