Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2021 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 :
23 : #include "runtime.h"
24 :
25 : #if defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
26 : #include <pthread.h>
27 : #endif
28 : #if defined(Q_OS_FREEBSD)
29 : #include <pthread_np.h> // Needed for pthread_setname_np on FreeBSD
30 : #endif
31 :
32 : #ifdef Q_OS_LINUX
33 : #include "log.h"
34 : #endif
35 :
36 : static thread_local std::string s_threadName;
37 :
38 140 : void muse::runtime::setThreadName(const std::string& name)
39 : {
40 140 : s_threadName = name;
41 : #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)
42 : // Set thread name through pthreads to aid debuggers that display such names.
43 : // Thread names are limited to 16 bytes on Linux, including the
44 : // terminating null.
45 140 : DO_ASSERT(name.length() <= 15);
46 140 : std::string truncated_name = name.length() > 15 ? name.substr(0, 15) : name;
47 140 : if (pthread_setname_np(pthread_self(), truncated_name.c_str()) > 0) {
48 0 : LOGW() << "Couldn't set thread name through pthreads";
49 : }
50 : #elif defined(Q_OS_MACOS)
51 : pthread_setname_np(name.c_str());
52 : #endif
53 140 : }
54 :
55 0 : const std::string& muse::runtime::threadName()
56 : {
57 0 : if (s_threadName.empty()) {
58 0 : static thread_local std::string id = toString(std::this_thread::get_id());
59 0 : return id;
60 : }
61 0 : return s_threadName;
62 : }
|