Bitcoin Core  24.99.0
P2P Digital Currency
threadnames.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 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 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <string>
10 #include <thread>
11 #include <utility>
12 
13 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
14 #include <pthread.h>
15 #include <pthread_np.h>
16 #endif
17 
18 #include <util/threadnames.h>
19 
20 #ifdef HAVE_SYS_PRCTL_H
21 #include <sys/prctl.h>
22 #endif
23 
26 static void SetThreadName(const char* name)
27 {
28 #if defined(PR_SET_NAME)
29  // Only the first 15 characters are used (16 - NUL terminator)
30  ::prctl(PR_SET_NAME, name, 0, 0, 0);
31 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
32  pthread_set_name_np(pthread_self(), name);
33 #elif defined(MAC_OSX)
34  pthread_setname_np(name);
35 #else
36  // Prevent warnings for unused parameters...
37  (void)name;
38 #endif
39 }
40 
41 // If we have thread_local, just keep thread ID and name in a thread_local
42 // global.
43 #if defined(HAVE_THREAD_LOCAL)
44 
45 static thread_local std::string g_thread_name;
46 const std::string& util::ThreadGetInternalName() { return g_thread_name; }
49 static void SetInternalName(std::string name) { g_thread_name = std::move(name); }
50 
51 // Without thread_local available, don't handle internal name at all.
52 #else
53 
54 static const std::string empty_string;
55 const std::string& util::ThreadGetInternalName() { return empty_string; }
56 static void SetInternalName(std::string name) { }
57 #endif
58 
59 void util::ThreadRename(std::string&& name)
60 {
61  SetThreadName(("b-" + name).c_str());
62  SetInternalName(std::move(name));
63 }
64 
65 void util::ThreadSetInternalName(std::string&& name)
66 {
67  SetInternalName(std::move(name));
68 }
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:65
const std::string & ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:55
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:59
const char * name
Definition: rest.cpp:46
static void SetInternalName(std::string name)
Definition: threadnames.cpp:56
static const std::string empty_string
Definition: threadnames.cpp:54
static void SetThreadName(const char *name)
Set the thread's name at the process level.
Definition: threadnames.cpp:26