rippled
Loading...
Searching...
No Matches
CurrentThreadName.cpp
1#include <xrpl/beast/core/CurrentThreadName.h>
2
3#include <string>
4#include <string_view>
5
6//------------------------------------------------------------------------------
7
8#if BOOST_OS_WINDOWS
9#include <process.h>
10#include <windows.h>
11
12namespace beast::detail {
13
14inline void
15setCurrentThreadNameImpl(std::string_view name)
16{
17#if DEBUG && BOOST_COMP_MSVC
18 // This technique is documented by Microsoft and works for all versions
19 // of Windows and Visual Studio provided that the process is being run
20 // under the Visual Studio debugger. For more details, see:
21 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code
22
23#pragma pack(push, 8)
24 struct THREADNAME_INFO
25 {
26 DWORD dwType;
27 LPCSTR szName;
28 DWORD dwThreadID;
29 DWORD dwFlags;
30 };
31#pragma pack(pop)
32
33 THREADNAME_INFO ni;
34
35 ni.dwType = 0x1000;
36 ni.szName = name.data();
37 ni.dwThreadID = GetCurrentThreadId();
38 ni.dwFlags = 0;
39
40#pragma warning(push)
41#pragma warning(disable : 6320 6322)
42 __try
43 {
44 RaiseException(
45 0x406d1388, 0, sizeof(ni) / sizeof(ULONG_PTR), (ULONG_PTR*)&ni);
46 }
47 __except (EXCEPTION_CONTINUE_EXECUTION)
48 {
49 }
50#pragma warning(pop)
51#endif
52}
53
54} // namespace beast::detail
55#endif // BOOST_OS_WINDOWS
56
57#if BOOST_OS_MACOS
58#include <pthread.h>
59
60namespace beast::detail {
61
62inline void
63setCurrentThreadNameImpl(std::string_view name)
64{
65 pthread_setname_np(name.data());
66}
67
68} // namespace beast::detail
69#endif // BOOST_OS_MACOS
70
71#if BOOST_OS_LINUX
72#include <pthread.h>
73
74#include <iostream>
75
76namespace beast::detail {
77
78inline void
79setCurrentThreadNameImpl(std::string_view name)
80{
81 // truncate and set the thread name.
82 char boundedName[maxThreadNameLength + 1];
84 boundedName,
85 sizeof(boundedName),
86 "%.*s",
87 static_cast<int>(maxThreadNameLength),
88 name.data());
89
90 pthread_setname_np(pthread_self(), boundedName);
91
92#ifdef TRUNCATED_THREAD_NAME_LOGS
93 if (name.size() > maxThreadNameLength)
94 {
95 std::cerr << "WARNING: Thread name \"" << name << "\" (length "
96 << name.size() << ") exceeds maximum of "
97 << maxThreadNameLength << " characters on Linux.\n";
98 }
99#endif
100}
101
102} // namespace beast::detail
103#endif // BOOST_OS_LINUX
104
105namespace beast {
106
107namespace detail {
109} // namespace detail
110
116
117void
119{
120 detail::threadName = name;
121 detail::setCurrentThreadNameImpl(name);
122}
123
124} // namespace beast
T data(T... args)
T snprintf(T... args)
thread_local std::string threadName
void setCurrentThreadName(std::string_view newThreadName)
Changes the name of the caller thread.
std::string getCurrentThreadName()
Returns the name of the caller thread.
T size(T... args)