Is there any way of setting the name of a thread in Linux?
My main purpose is it would be helpful while debugging, and also nice if that name was exposed through e.g. /proc/$PID/task/$TID/...
Is there any way of setting the name of a thread in Linux?
My main purpose is it would be helpful while debugging, and also nice if that name was exposed through e.g. /proc/$PID/task/$TID/...
Use the
prctl(2)
function with the optionPR_SET_NAME
(see the docs).Note that old versions of the docs are a bit confusing. They say
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:or in between the
()
ofcat /proc/$PID/task/$TID/stat
:or from GDB
info threads
between double quotes:As of glibc v2.12, you can use
pthread_setname_np
andpthread_getname_np
to set/get the thread name.These interfaces are available on a few other POSIX systems (BSD, QNX, Mac) in various slightly different forms.
Setting the name will be something like this:
And you can get the name back:
As you can see it's not completely portable between POSIX systems, but as far as I can tell across linux it should be consistent. Apart from Mac OS X (where you can only do it from within the thread), the others are at least simple to adapt for cross-platform code.
Sources:
/Developer/SDKs/MacOSX10.7.sdk/usr/include/pthread.h
You can implement this yourself by creating a dictionary mapping
pthread_t
tostd::string
, and then associate the result of pthread_self() with the name that you want to assign to the current thread. Note that, if you do that, you will need to use a mutex or other synchronization primitive to prevent multiple threads from concurrently modifying the dictionary (unless your dictionary implementation already does this for you). You could also use thread-specific variables (see pthread_key_create, pthread_setspecific, pthread_getspecific, and pthread_key_delete) in order to save the name of the current thread; however, you won't be able to access the names of other threads if you do that (whereas, with a dictionary, you can iterate over all thread id/name pairs from any thread).