Line data Source code
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) 6 : #include <config/bitcoin-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 : 24 : //! Set the thread's name at the process level. Does not affect the 25 : //! internal name. 26 4 : 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 4 : ::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 4 : } 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 4 : static thread_local std::string g_thread_name; 46 1 : const std::string& util::ThreadGetInternalName() { return g_thread_name; } 47 : //! Set the in-memory internal name for this thread. Does not affect the process 48 : //! name. 49 4 : 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 4 : void util::ThreadRename(std::string&& name) 60 : { 61 4 : SetThreadName(("b-" + name).c_str()); 62 4 : SetInternalName(std::move(name)); 63 4 : } 64 : 65 0 : void util::ThreadSetInternalName(std::string&& name) 66 : { 67 0 : SetInternalName(std::move(name)); 68 0 : }