Skip to content

set thread name #85

@vinniefalco

Description

@vinniefalco

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 null

macOS:

#include <pthread.h>
pthread_setname_np("MyThread");  // note: no thread handle parameter

Portable 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 SetThreadDescription requires linking against kernel32.lib and only works on Windows 10 1607+
  • For older Windows, there's an SEH exception trick (RaiseException with 0x406D1388) but it only works with a debugger attached
  • Boost.Thread doesn't provide this either
  • Some libraries like fmt or spdlog have their own implementations you could reference

Would you like me to search your codebase for any existing thread naming utilities?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions