Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name a thread in Linux? [duplicate]

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?

like image 771
user9876 Avatar asked Apr 22 '09 16:04

user9876


People also ask

How do you name a thread in Linux?

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').

How do you give a thread a name?

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.

Does clone create new 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.

How do I see threads in Linux?

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.


2 Answers

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) 
like image 140
Fusspawn Avatar answered Sep 21 '22 15:09

Fusspawn


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.

like image 28
lothar Avatar answered Sep 18 '22 15:09

lothar