Skip to content

Commit

Permalink
add set_thread_name and set_current_thread_name
Browse files Browse the repository at this point in the history
  • Loading branch information
pablohoch committed Nov 4, 2024
1 parent f76f708 commit 9c44a5a
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions include/utl/set_thread_name.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#pragma once

#include <string>
#include <thread>

#if defined(_WIN32)

namespace utl {

inline void set_thread_name(HANDLE hThread, std::string const& name) {
auto size_needed =
MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
auto wname = std::wstring(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &wname[0], size_needed);
SetThreadDescription(hThread, wname.c_str());
}

inline void set_thread_name(std::thread& thread, std::string const& name) {
return set_thread_name(thread.native_handle(), name);
}

inline void set_current_thread_name(std::string const& name) {
return set_thread_name(GetCurrentThread(), name);
}

} // namespace utl

#elif defined(__APPLE__)

#include <pthread.h>

namespace utl {

inline void set_thread_name(std::thread&, std::string const&) {}

inline void set_current_thread_name(std::string const& name) {
pthread_setname_np(name.data());
}

} // namespace utl

#else

#include <pthread.h>

namespace utl {

inline void set_thread_name(std::thread& thread, std::string const& name) {
pthread_setname_np(thread.native_handle(), name.data());
}

inline void set_current_thread_name(std::string const& name) {
pthread_setname_np(pthread_self(), name.data());
}

} // namespace utl

#endif

0 comments on commit 9c44a5a

Please sign in to comment.