views:

1987

answers:

2

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?

+7  A: 

Posix Threads?

This evidently wont compile, But it will give you an idea of where to go hunting, Im note even sure its the right PR_ command, But i think it is, Its been a while..

  #include <sys/prctl.h>
  prctl(PR_SET_NAME,"<null> terminated string",0,0,0)
Fusspawn
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.
user9876
Glad it worked, I wasnt sure if it was even the right Constant for it, :)
Fusspawn
I've always identified threads based on the start function as shown in the thread's stack-trace. Nice to know there's a clean alternative.
veefu
Further investigation shows that busybox's "top" and "ps" don't report thread names. You need the full versions from the "procps" package.
user9876
+4  A: 

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.

lothar