std::thread - naming your thread
C++MultithreadingC++11C++ Problem Overview
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?
C++ Solutions
Solution 1 - C++
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.
Solution 2 - C++
An attempt at making a wrapper to deal with many Linuxes as well as Windows. Please edit as needed.
#ifdef _WIN32
#include
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName(uint32_t dwThreadID, const char* threadName)
{
// DWORD dwThreadID = ::GetThreadId( static_cast<HANDLE>( t.native_handle() ) );
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
void SetThreadName( const char* threadName)
{
SetThreadName(GetCurrentThreadId(),threadName);
}
void SetThreadName( std::thread* thread, const char* threadName)
{
DWORD threadId = ::GetThreadId( static_cast<HANDLE>( thread->native_handle() ) );
SetThreadName(threadId,threadName);
}
#elif defined(__linux__)
#include <sys/prctl.h>
void SetThreadName( const char* threadName)
{
prctl(PR_SET_NAME,threadName,0,0,0);
}
#else
void SetThreadName(std::thread* thread, const char* threadName)
{
auto handle = thread->native_handle();
pthread_setname_np(handle,threadName);
}
#endif
Solution 3 - C++
You can use std::thread::native_handle
to get the underlaying implementation defined thread. There is no standard function for that natively.
You can find an example here.
Solution 4 - C++
For windows [debugger], you can easily use the "normal" method; http://msdn.microsoft.com/en-gb/library/xcb2z8hs.aspx
Just need the thread id which you can obtain via
#include <windows.h>
DWORD ThreadId = ::GetThreadId( static_cast<HANDLE>( mThread.native_handle() ) );
Solution 5 - C++
I've both seen this done in a system predating c++11 (where we basically invented our own Thread class that was very similar to std::thread) and in one I wrote fairly recently.
Basically, the pool really puts std::thread 2 layers down- you have a PoolThread class that contains a std::thread plus metadata like its name, ID, etc. and the the control structure that links it to its controlling pool, and the ThreadPool itself. You want to use thread pools in most threaded code for several reasons:
- You can hide all the explicit "detach", "join", start thread on std::thread construction, etc. from users. That produces MUCH safer & cleaner code.
- Better resource management: Too many threads will cripple performance even more than having too few. A well-built pool can do advanced things like automatic load balancing and cleaning-up hung or deadlocked threads.
- Thread reuse: std::thread by itself is easiest to use by running every parallel task on its own thread. But thread creation & destruction are expensive, and can easily swamp the speed boost from parallel processing if you're not careful. So, it usually makes more sense to have pool threads that pull work tasks from a queue and only exit after receiving some signal.
- Error handling: std::thread is just an execution context. If the task you're running on it throws an un-handled exception or std::thread ITSELF fails, the process will just crash right there. To do fault-tolerant multithreading, you need a Pool or something similar that can quickly catch such things and at least emit meaningful error messages before the process dies.
Solution 6 - C++
In header file do:
const std::string & ThreadName(const std::string name="");
In src file do:
const std::string & ThreadName(const std::string name)
{
static std::atomic_int threadCount{0};
const thread_local std::string _name = name + std::to_string(threadCount.fetch_add(1));
return _name;
}
Usage:
void myThread()
{
ThreadName("myThread"); // Call once at very beginning of your thread creation
...
std::cout << ThreadName() << std::endl; // Anyplace in your code
}