/tmp/bitcoin/src/util/threadnames.cpp
Line | Count | Source |
1 | | // Copyright (c) 2018-present The Bitcoin Core developers |
2 | | // Distributed under the MIT software license, see the accompanying |
3 | | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
4 | | |
5 | | #include <util/threadnames.h> |
6 | | |
7 | | #include <algorithm> |
8 | | #include <cstring> |
9 | | #include <string> |
10 | | |
11 | | #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) |
12 | | #include <pthread.h> |
13 | | #include <pthread_np.h> |
14 | | #endif |
15 | | |
16 | | #if __has_include(<sys/prctl.h>) |
17 | | #include <sys/prctl.h> |
18 | | #endif |
19 | | |
20 | | //! Set the thread's name at the process level. Does not affect the |
21 | | //! internal name. |
22 | | static void SetThreadName(const char* name) |
23 | 12.0k | { |
24 | 12.0k | #if defined(PR_SET_NAME) |
25 | | // Only the first 15 characters are used (16 - NUL terminator) |
26 | 12.0k | ::prctl(PR_SET_NAME, name, 0, 0, 0); |
27 | | #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) |
28 | | pthread_set_name_np(pthread_self(), name); |
29 | | #elif defined(__APPLE__) |
30 | | pthread_setname_np(name); |
31 | | #else |
32 | | // Prevent warnings for unused parameters... |
33 | | (void)name; |
34 | | #endif |
35 | 12.0k | } |
36 | | |
37 | | /** |
38 | | * The name of the thread. We use char array instead of std::string to avoid |
39 | | * complications with running a destructor when the thread exits. Avoid adding |
40 | | * other thread_local variables. |
41 | | * @see https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=278701 |
42 | | */ |
43 | | static thread_local char g_thread_name[128]{'\0'}; |
44 | 88.6M | std::string util::ThreadGetInternalName() { return g_thread_name; } |
45 | | //! Set the in-memory internal name for this thread. Does not affect the process |
46 | | //! name. |
47 | | static void SetInternalName(const std::string& name) |
48 | 13.2k | { |
49 | 13.2k | const size_t copy_bytes{std::min(sizeof(g_thread_name) - 1, name.length())}; |
50 | 13.2k | std::memcpy(g_thread_name, name.data(), copy_bytes); |
51 | 13.2k | g_thread_name[copy_bytes] = '\0'; |
52 | 13.2k | } |
53 | | |
54 | | void util::ThreadRename(const std::string& name) |
55 | 12.0k | { |
56 | 12.0k | SetThreadName(("b-" + name).c_str()); |
57 | 12.0k | SetInternalName(name); |
58 | 12.0k | } |
59 | | |
60 | | void util::ThreadSetInternalName(const std::string& name) |
61 | 1.17k | { |
62 | 1.17k | SetInternalName(name); |
63 | 1.17k | } |