12 #include <mrpt/config.h> 16 #if defined(MRPT_OS_WINDOWS) 22 #elif defined(MRPT_OS_LINUX) 23 #include <sys/prctl.h> 25 static void SetThreadName(std::thread& thread,
const char* threadName)
27 auto handle = thread.native_handle();
28 pthread_setname_np(handle, threadName);
31 static std::string GetThreadName(std::thread& thread)
33 auto handle = thread.native_handle();
36 pthread_getname_np(handle, buf,
sizeof(buf));
37 return std::string(buf);
40 static void SetThreadName(
const char* threadName)
42 prctl(PR_SET_NAME, threadName, 0L, 0L, 0L);
44 static std::string GetThreadName()
47 prctl(PR_GET_NAME, buf, 0L, 0L, 0L);
48 return std::string(buf);
54 #if defined(MRPT_OS_WINDOWS) 56 std::mbstowcs(wName, name.c_str(),
sizeof(wName) /
sizeof(wName[0]));
57 SetThreadDescription(GetCurrentThread(), wName);
58 #elif defined(MRPT_OS_LINUX) 59 SetThreadName(name.c_str());
65 #if defined(MRPT_OS_WINDOWS) 67 std::mbstowcs(wName, name.c_str(),
sizeof(wName) /
sizeof(wName[0]));
68 SetThreadDescription(theThread.native_handle(), wName);
69 #elif defined(MRPT_OS_LINUX) 70 SetThreadName(theThread, name.c_str());
74 #if defined(MRPT_OS_WINDOWS) 75 static std::string w2cstr(
wchar_t** wstrnc)
77 const wchar_t** wstr =
const_cast<const wchar_t**
>(wstrnc);
79 std::mbstate_t state = std::mbstate_t();
80 std::size_t len = 1 + std::wcsrtombs(
nullptr, wstr, 0, &state);
81 std::vector<char> mbstr(len);
82 std::wcsrtombs(&mbstr[0], wstr, mbstr.size(), &state);
83 return std::string(mbstr.data());
89 #if defined(MRPT_OS_WINDOWS) 90 std::string ret =
"NoName";
92 HRESULT hr = GetThreadDescription(GetCurrentThread(), &str);
95 ret = w2cstr(reinterpret_cast<wchar_t**>(&str));
99 #elif defined(MRPT_OS_LINUX) 100 return GetThreadName();
102 return std::string(
"");
108 #if defined(MRPT_OS_WINDOWS) 109 std::string ret =
"NoName";
111 HRESULT hr = GetThreadDescription(theThread.native_handle(), &str);
114 ret = w2cstr(reinterpret_cast<wchar_t**>(&str));
118 #elif defined(MRPT_OS_LINUX) 119 return GetThreadName(theThread);
121 return std::string(
"");
void thread_name(const std::string &name, std::thread &theThread)
Sets the name of the given thread; useful for debuggers.