Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread - naming your thread

The new C++ has this std::thread type. Works like a charm. Now I would like to give each thread a name for more easy debugging (like java allows you to). With pthreads I would do:

pthread_setname_np(pthread_self(), "thread_name"); 

but how can I do this with c++0x? I know it uses pthreads underneath on Linux systems, but I would like to make my application portable. Is it possible at all?

like image 797
Folkert van Heusden Avatar asked Apr 12 '12 10:04

Folkert van Heusden


People also ask

How do you give a thread a name in C++?

With pthreads I would do: pthread_setname_np(pthread_self(), "thread_name");

How do I set my Pthread name?

The pthread_setname_np() function can be used to set a unique name for a thread, which can be useful for debugging multithreaded applications. The thread name is a meaningful C language string, whose length is restricted to 16 characters, including the terminating null byte ('\0').

Is std :: thread copyable?

std::thread::operator= thread objects cannot be copied (2).

How do I name a thread in Windows?

There are two ways to set a thread name. The first is via the SetThreadDescription function. The second is by throwing a particular exception while the Visual Studio debugger is attached to the process.


1 Answers

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.

like image 94
Mike Seymour Avatar answered Oct 09 '22 20:10

Mike Seymour