Bitcoin Core 32.99.0
P2P Digital Currency
threadnames.cpp
Go to the documentation of this file.
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 <bitcoin-build-config.h> // IWYU pragma: keep
6
7#include <util/threadnames.h>
8#include <util/check.h>
9
10#include <algorithm>
11#include <cstring>
12#include <string>
13
14#if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
15#include <pthread.h>
16#include <pthread_np.h>
17#endif
18
19#if __has_include(<sys/prctl.h>)
20#include <sys/prctl.h>
21#endif
22
23#ifdef HAVE_SETTHREADDESCRIPTION
24#include <windows.h>
25#endif
26
29static void SetThreadName(const char* name)
30{
31#if defined(PR_SET_NAME)
32 // Only the first 15 characters are used (16 - NUL terminator)
33 ::prctl(PR_SET_NAME, name, 0, 0, 0);
34#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
35 pthread_set_name_np(pthread_self(), name);
36#elif defined(__APPLE__)
37 pthread_setname_np(name);
38#elif defined(HAVE_SETTHREADDESCRIPTION)
39 // Thread names are ASCII-only, so widening each character is sufficient as
40 // a conversion to UTF-16.
41 const std::wstring wname{name, name + std::strlen(name)};
42 ::SetThreadDescription(::GetCurrentThread(), wname.c_str());
43#else
44 // Prevent warnings for unused parameters...
45 (void)name;
46#endif
47}
48
55static thread_local char g_thread_name[128]{'\0'};
59static void SetInternalName(const std::string& name)
60{
61 const size_t copy_bytes{std::min(sizeof(g_thread_name) - 1, name.length())};
62 std::memcpy(g_thread_name, name.data(), copy_bytes);
63 g_thread_name[copy_bytes] = '\0';
64}
65
66void util::ThreadRename(const std::string& name)
67{
68 Assume(name.size() <= 13); // Linux keeps 15 bytes
69 SetThreadName(("b-" + name).c_str());
71}
72
73void util::ThreadSetInternalName(const std::string& name)
74{
76}
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:66
std::string ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:56
void ThreadSetInternalName(const std::string &)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:73
const char * name
Definition: rest.cpp:71
static thread_local char g_thread_name[128]
The name of the thread.
Definition: threadnames.cpp:55
static void SetInternalName(const std::string &name)
Set the in-memory internal name for this thread.
Definition: threadnames.cpp:59
static void SetThreadName(const char *name)
Set the thread's name at the process level.
Definition: threadnames.cpp:29