I want to set the name of the current execution thread in C++ code; the underlying threading library is pthreads.
In case I have the std::thread handle of a thread, I can get the native pthreads handle using std::thread::native_handle
, then pass this to pthread_setname_np
to set the thread name.
auto t = std::thread(call_from_thread);
pthread_setname_np(t.native_handle(), my_thread_name.c_str());
But how can I set the thread name in cases where I do not have the std::thread
handle available. For example when the thread is started by some other library, and I am writing a callback that will be executed by that thread, can I write some code within the callback that sets a custom name for the thread executing it?
I know that I can get the current thread std::thread::id
object using std::this_thread::get_id
. Is there a way to convert this into a pthread native handle that can then be used to set the custom thread name?
Unless portability is wanted, and the target is only POSIX systems with POSIX threads, the id could easily be obtained with pthread_self
.