-
Notifications
You must be signed in to change notification settings - Fork 10
Open
Labels
Description
Would be nice to have a thread name setting facility for things like io_context or thread_pool threads to know what is what in the debugger. The difficulty is trying to roll this up into something automatic for user-defined threads.
Thread naming isn't standardized in C++, so you need platform-specific code. Here's the portable approach:
Windows (10 1607+):
#include <windows.h>
SetThreadDescription(GetCurrentThread(), L"MyThread");Linux/FreeBSD:
#include <pthread.h>
pthread_setname_np(pthread_self(), "MyThread"); // max 16 chars including nullmacOS:
#include <pthread.h>
pthread_setname_np("MyThread"); // note: no thread handle parameterPortable wrapper:
#include <string_view>
inline void set_thread_name(std::string_view name)
{
#if defined(_WIN32)
// Windows 10 1607+ only
std::wstring wname(name.begin(), name.end());
SetThreadDescription(GetCurrentThread(), wname.c_str());
#elif defined(__APPLE__)
pthread_setname_np(std::string(name.substr(0, 63)).c_str());
#elif defined(__linux__) || defined(__FreeBSD__)
// Linux has 16-char limit including null terminator
char buf[16];
auto len = std::min(name.size(), size_t{15});
std::copy_n(name.data(), len, buf);
buf[len] = '\0';
pthread_setname_np(pthread_self(), buf);
#endif
}Notes:
- Linux has a strict 15-character limit (16 with null terminator)
- Windows
SetThreadDescriptionrequires linking againstkernel32.liband only works on Windows 10 1607+ - For older Windows, there's an SEH exception trick (
RaiseExceptionwith0x406D1388) but it only works with a debugger attached - Boost.Thread doesn't provide this either
- Some libraries like
fmtorspdloghave their own implementations you could reference
Would you like me to search your codebase for any existing thread naming utilities?