C++: Set name of the thread
Did you know that you can set an arbitrary name for a thread and make it visible to the debugger?
For example, when debugging with JetBrains CLion, the thread name is visible in the threads dropdown.
This is how it’s done:
#if defined(__APPLE__)
#include <pthread.h>
#endif
#if defined(__linux__)
#include <sys/prctl.h>
#endif
#ifdef _WIN32
#include <windows.h>
typedef HRESULT(WINAPI* pfnSetThreadDescription)(HANDLE, PCWSTR);
#endif
void setThreadName(const char* name) {
#if defined(_WIN32)
(void)name;
wchar_t wname[256];
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, wname, 256) > 0) {
HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll");
if (kernel32) {
pfnSetThreadDescription pSetThreadDescription =
(pfnSetThreadDescription)GetProcAddress(kernel32, "SetThreadDescription");
if (pSetThreadDescription) {
pSetThreadDescription(GetCurrentThread(), wname);
}
}
}
#elif defined(__APPLE__)
pthread_setname_np(name);
#elif defined(__linux__)
prctl(PR_SET_NAME, name);
#endif
}