diff --git a/rtc_base/BUILD.gn b/rtc_base/BUILD.gn index a61ede4ac9..2d90898ce7 100644 --- a/rtc_base/BUILD.gn +++ b/rtc_base/BUILD.gn @@ -154,6 +154,7 @@ rtc_library("platform_thread_types") { "platform_thread_types.cc", "platform_thread_types.h", ] + deps = [ ":macromagic" ] } rtc_source_set("refcount") { diff --git a/rtc_base/platform_thread_types.cc b/rtc_base/platform_thread_types.cc index ed4a228262..a2f8d353d1 100644 --- a/rtc_base/platform_thread_types.cc +++ b/rtc_base/platform_thread_types.cc @@ -15,6 +15,10 @@ #include #endif +#if defined(WEBRTC_WIN) +#include "rtc_base/arraysize.h" +#endif + namespace rtc { PlatformThreadId CurrentThreadId() { @@ -58,6 +62,24 @@ bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) { void SetCurrentThreadName(const char* name) { #if defined(WEBRTC_WIN) + // The SetThreadDescription API works even if no debugger is attached. + // The names set with this API also show up in ETW traces. Very handy. + static auto set_thread_description_func = + reinterpret_cast(::GetProcAddress( + ::GetModuleHandleA("Kernel32.dll"), "SetThreadDescription")); + if (set_thread_description_func) { + // Convert from ASCII to UTF-16. + wchar_t wide_thread_name[64]; + for (size_t i = 0; i < arraysize(wide_thread_name) - 1; ++i) { + wide_thread_name[i] = name[i]; + if (wide_thread_name[i] == L'\0') + break; + } + // Guarantee null-termination. + wide_thread_name[arraysize(wide_thread_name) - 1] = L'\0'; + set_thread_description_func(::GetCurrentThread(), wide_thread_name); + } + // For details see: // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code #pragma pack(push, 8)