xref: /aosp_15_r20/external/perfetto/include/perfetto/base/thread_utils.h (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2018 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_BASE_THREAD_UTILS_H_
18 #define INCLUDE_PERFETTO_BASE_THREAD_UTILS_H_
19 
20 #include <stdint.h>
21 
22 #include "perfetto/base/build_config.h"
23 #include "perfetto/base/export.h"
24 
25 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
26 extern "C" {
27 // Prototype extracted from the Windows SDK to avoid including windows.h.
28 __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId();
29 }
30 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA)
31 #include <zircon/types.h>
32 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
33     PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
34 #include <sys/syscall.h>
35 #include <sys/types.h>
36 #include <unistd.h>
37 #else
38 #include <pthread.h>
39 #endif
40 
41 namespace perfetto {
42 namespace base {
43 
44 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
45 using PlatformThreadId = pid_t;
GetThreadId()46 inline PlatformThreadId GetThreadId() {
47   return gettid();
48 }
49 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX)
50 using PlatformThreadId = pid_t;
51 inline PlatformThreadId GetThreadId() {
52   return static_cast<pid_t>(syscall(__NR_gettid));
53 }
54 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA)
55 using PlatformThreadId = zx_koid_t;
56 // Not inlined because the result is cached internally.
57 PERFETTO_EXPORT_COMPONENT PlatformThreadId GetThreadId();
58 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
59 using PlatformThreadId = uint64_t;
60 inline PlatformThreadId GetThreadId() {
61   uint64_t tid;
62   pthread_threadid_np(nullptr, &tid);
63   return tid;
64 }
65 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
66 using PlatformThreadId = uint64_t;
67 inline PlatformThreadId GetThreadId() {
68   return static_cast<uint64_t>(GetCurrentThreadId());
69 }
70 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
71 using PlatformThreadId = pid_t;
72 inline PlatformThreadId GetThreadId() {
73   return reinterpret_cast<int32_t>(pthread_self());
74 }
75 #else  // Default to pthreads in case no OS is set.
76 using PlatformThreadId = pthread_t;
77 inline PlatformThreadId GetThreadId() {
78   return pthread_self();
79 }
80 #endif
81 
82 }  // namespace base
83 }  // namespace perfetto
84 
85 #endif  // INCLUDE_PERFETTO_BASE_THREAD_UTILS_H_
86