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?
The pthread_setname_np() function can be used to set a unique name for a thread, which can be useful for debugging multithreaded applications. The thread name is a meaningful C language string, whose length is restricted to 16 characters, including the terminating null byte ('\0').
Naming Thread By we can change the name of the thread by using the setName() method. The syntax of setName() and getName() methods are given below: public String getName(): is used to return the name of a thread. public void setName(String name): is used to change the name of a thread.
This thread is the leader of the new thread group. A new thread created with CLONE_THREAD has the same parent process as the process that made the clone call (i.e., like CLONE_PARENT), so that calls to getppid(2) return the same value for all of the threads in a thread group.
The top command can show a real-time view of individual threads. To enable thread views in the top output, invoke top with "-H" option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing 'H' key.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With