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

前端 未结 3 621
独厮守ぢ
独厮守ぢ 2020-11-28 03:59

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

3条回答
  •  渐次进展
    2020-11-28 04:32

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

提交回复
热议问题