How to Name a Thread in Linux

How to set the name of a thread in Linux pthreads?

Use the prctl(2) function with the option PR_SET_NAME (see the docs).

Note that old versions of the docs are a bit confusing. They say

Set the process name for the calling process

but since threads are light weight processes (LWP) on Linux, one thread is one process in this case.

You can see the thread name with ps -o cmd or with:

cat /proc/$PID/task/$TID/comm

or in between the () of cat /proc/$PID/task/$TID/stat:

4223 (kjournald) S 1 1 1 0...

or from GDB info threads between double quotes:

* 1    Thread 0x7ffff7fc7700 (LWP 6575) "kjournald" 0x00007ffff78bc30d in nanosleep () at ../sysdeps/unix/syscall-template.S:84                                                                                  

How to name a thread in Linux?

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)

How can I get the whole thread name when I use `ps -T -p [pid]`

The thread name length is restricted to 16 characters (including the terminating null byte \0). If the length, including the \0, exceeds 16 bytes, the string is silently truncated before storing it.

See pthread_setname_np and proc.5 -> find /proc/[pid]/task/[tid]/comm.

Related:

How to get the full executable name of a running process in Linux

How to set pthread name at the time of creation?

how I can set the thread name at the time I create the thread using pthread_create()?

That is not possible. Instead you can use a barrier or mutex to synchronize the child thread until it's ready to be run. Or you can set the thread name from inside the thread (if any other threads are not using it's name).

Do not to use pthread_setname_np. This is a nonstandard GNU extension. The _np suffix literally means "non-portable". Write portable code and instead use your own place where you store your thread names.

std::thread - naming your thread

A portable way to do this is to maintain a map of names, keyed by the thread's ID, obtained from thread::get_id(). Alternatively, as suggested in the comments, you could use a thread_local variable, if you only need to access the name from within the thread.

If you didn't need portability, then you could get the underlying pthread_t from thread::native_handle() and do whatever platform-specific shenanigans you like with that. Be aware that the _np on the thread naming functions means "not posix", so they aren't guaranteed to be available on all pthreads implementations.

How to set custom name of this thread?

Unless portability is wanted, and the target is only POSIX systems with POSIX threads, the id could easily be obtained with pthread_self.



Related Topics



Leave a reply



Submit