1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_ 18 #define INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_ 19 20 #include <string> 21 22 #include "perfetto/base/build_config.h" 23 24 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ 25 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ 26 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) 27 #include <pthread.h> 28 #include <string.h> 29 #include <algorithm> 30 #endif 31 32 // Internal implementation utils that aren't as widely useful/supported as 33 // base/thread_utils.h. 34 35 namespace perfetto { 36 namespace base { 37 38 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ 39 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \ 40 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) 41 // Sets the "comm" of the calling thread to the first 15 chars of the given 42 // string. MaybeSetThreadName(const std::string & name)43inline bool MaybeSetThreadName(const std::string& name) { 44 char buf[16] = {}; 45 size_t sz = std::min(name.size(), static_cast<size_t>(15)); 46 strncpy(buf, name.c_str(), sz); 47 48 #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) 49 return pthread_setname_np(buf) == 0; 50 #else 51 return pthread_setname_np(pthread_self(), buf) == 0; 52 #endif 53 } 54 #else 55 inline void MaybeSetThreadName(const std::string&) {} 56 #endif 57 58 } // namespace base 59 } // namespace perfetto 60 61 #endif // INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_ 62