tags:

views:

299

answers:

2

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 /proc/

A: 

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

Note that 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 in /proc/$PID/stat between the ():

4223 (kjournald) S 1 1 1 0...
Aaron Digulla
Note that the actual thread names will be in /proc/$PID/tasks/$TID/stat
nos
+2  A: 

You can implement this yourself by creating a dictionary mapping pthread_t to std::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).

Michael Aaron Safyan
Note that this solution is portable across Linux, Mac OS X, and all systems that conform to the Single UNIX Specification. (A suggestion posted by Aaron Digulla to use "prctl" is not portable).
Michael Aaron Safyan