1 // Copyright 2012 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // WARNING: You should *NOT* be using this class directly. PlatformThread is 6 // the low-level platform-specific abstraction to the OS's threading interface. 7 // You should instead be using a message-loop driven Thread, see thread.h. 8 9 #ifndef BASE_THREADING_PLATFORM_THREAD_H_ 10 #define BASE_THREADING_PLATFORM_THREAD_H_ 11 12 #include <stddef.h> 13 14 #include <iosfwd> 15 #include <optional> 16 #include <type_traits> 17 18 #include "base/base_export.h" 19 #include "base/message_loop/message_pump_type.h" 20 #include "base/process/process_handle.h" 21 #include "base/threading/platform_thread_ref.h" 22 #include "base/time/time.h" 23 #include "base/types/strong_alias.h" 24 #include "build/build_config.h" 25 #include "build/chromeos_buildflags.h" 26 27 #if BUILDFLAG(IS_WIN) 28 #include "base/win/windows_types.h" 29 #elif BUILDFLAG(IS_FUCHSIA) 30 #include <zircon/types.h> 31 #elif BUILDFLAG(IS_APPLE) 32 #include <mach/mach_types.h> 33 #elif BUILDFLAG(IS_POSIX) 34 #include <pthread.h> 35 #include <unistd.h> 36 #endif 37 38 #if BUILDFLAG(IS_CHROMEOS) 39 #include "base/feature_list.h" 40 #endif 41 42 namespace base { 43 44 // Used for logging. Always an integer value. 45 #if BUILDFLAG(IS_WIN) 46 typedef DWORD PlatformThreadId; 47 #elif BUILDFLAG(IS_FUCHSIA) 48 typedef zx_koid_t PlatformThreadId; 49 #elif BUILDFLAG(IS_APPLE) 50 typedef mach_port_t PlatformThreadId; 51 #elif BUILDFLAG(IS_POSIX) 52 typedef pid_t PlatformThreadId; 53 #endif 54 static_assert(std::is_integral_v<PlatformThreadId>, "Always an integer value."); 55 56 // Used to operate on threads. 57 class PlatformThreadHandle { 58 public: 59 #if BUILDFLAG(IS_WIN) 60 typedef void* Handle; 61 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) 62 typedef pthread_t Handle; 63 #endif 64 PlatformThreadHandle()65 constexpr PlatformThreadHandle() : handle_(0) {} 66 PlatformThreadHandle(Handle handle)67 explicit constexpr PlatformThreadHandle(Handle handle) : handle_(handle) {} 68 is_equal(const PlatformThreadHandle & other)69 bool is_equal(const PlatformThreadHandle& other) const { 70 return handle_ == other.handle_; 71 } 72 is_null()73 bool is_null() const { 74 return !handle_; 75 } 76 platform_handle()77 Handle platform_handle() const { 78 return handle_; 79 } 80 81 private: 82 Handle handle_; 83 }; 84 85 const PlatformThreadId kInvalidThreadId(0); 86 87 // Valid values for `thread_type` of Thread::Options, SimpleThread::Options, 88 // and SetCurrentThreadType(), listed in increasing order of importance. 89 // 90 // It is up to each platform-specific implementation what these translate to. 91 // Callers should avoid setting different ThreadTypes on different platforms 92 // (ifdefs) at all cost, instead the platform differences should be encoded in 93 // the platform-specific implementations. Some implementations may treat 94 // adjacent ThreadTypes in this enum as equivalent. 95 // 96 // Reach out to //base/task/OWNERS (scheduler-dev@chromium.org) before changing 97 // thread type assignments in your component, as such decisions affect the whole 98 // of Chrome. 99 // 100 // Refer to PlatformThreadTest.SetCurrentThreadTypeTest in 101 // platform_thread_unittest.cc for the most up-to-date state of each platform's 102 // handling of ThreadType. 103 enum class ThreadType : int { 104 // Suitable for threads that have the least urgency and lowest priority, and 105 // can be interrupted or delayed by other types. 106 kBackground, 107 // Suitable for threads that are less important than normal type, and can be 108 // interrupted or delayed by threads with kDefault type. 109 kUtility, 110 // Suitable for threads that produce user-visible artifacts but aren't 111 // latency sensitive. The underlying platform will try to be economic 112 // in its usage of resources for this thread, if possible. 113 kResourceEfficient, 114 // Default type. The thread priority or quality of service will be set to 115 // platform default. In Chrome, this is suitable for handling user 116 // interactions (input), only display and audio can get a higher priority. 117 kDefault, 118 // Suitable for display critical threads, ie. threads critical to compositing 119 // and presenting the foreground content. 120 kDisplayCritical, 121 // Suitable for low-latency, glitch-resistant audio. 122 kRealtimeAudio, 123 kMaxValue = kRealtimeAudio, 124 }; 125 126 // Cross-platform mapping of physical thread priorities. Used by tests to verify 127 // the underlying effects of SetCurrentThreadType. 128 enum class ThreadPriorityForTest : int { 129 kBackground, 130 kUtility, 131 kResourceEfficient, 132 kNormal, 133 kCompositing, 134 kDisplay, 135 kRealtimeAudio, 136 kMaxValue = kRealtimeAudio, 137 }; 138 139 // A namespace for low-level thread functions. 140 class BASE_EXPORT PlatformThreadBase { 141 public: 142 // Implement this interface to run code on a background thread. Your 143 // ThreadMain method will be called on the newly created thread. 144 class BASE_EXPORT Delegate { 145 public: 146 virtual void ThreadMain() = 0; 147 148 #if BUILDFLAG(IS_APPLE) 149 // TODO: Move this to the PlatformThreadApple class. 150 // The interval at which the thread expects to have work to do. Zero if 151 // unknown. (Example: audio buffer duration for real-time audio.) Is used to 152 // optimize the thread real-time behavior. Is called on the newly created 153 // thread before ThreadMain(). 154 virtual TimeDelta GetRealtimePeriod(); 155 #endif 156 157 protected: 158 virtual ~Delegate() = default; 159 }; 160 161 PlatformThreadBase() = delete; 162 PlatformThreadBase(const PlatformThreadBase&) = delete; 163 PlatformThreadBase& operator=(const PlatformThreadBase&) = delete; 164 165 // Gets the current thread id, which may be useful for logging purposes. 166 static PlatformThreadId CurrentId(); 167 168 // Gets the current thread reference, which can be used to check if 169 // we're on the right thread quickly. 170 static PlatformThreadRef CurrentRef(); 171 172 // Get the handle representing the current thread. On Windows, this is a 173 // pseudo handle constant which will always represent the thread using it and 174 // hence should not be shared with other threads nor be used to differentiate 175 // the current thread from another. 176 static PlatformThreadHandle CurrentHandle(); 177 178 // Yield the current thread so another thread can be scheduled. 179 // 180 // Note: this is likely not the right call to make in most situations. If this 181 // is part of a spin loop, consider base::Lock, which likely has better tail 182 // latency. Yielding the thread has different effects depending on the 183 // platform, system load, etc., and can result in yielding the CPU for less 184 // than 1us, or many tens of ms. 185 static void YieldCurrentThread(); 186 187 // Sleeps for the specified duration (real-time; ignores time overrides). 188 // Note: The sleep duration may be in base::Time or base::TimeTicks, depending 189 // on platform. If you're looking to use this in unit tests testing delayed 190 // tasks, this will be unreliable - instead, use 191 // base::test::TaskEnvironment with MOCK_TIME mode. 192 static void Sleep(base::TimeDelta duration); 193 194 // Sets the thread name visible to debuggers/tools. This will try to 195 // initialize the context for current thread unless it's a WorkerThread. 196 static void SetName(const std::string& name); 197 198 // Gets the thread name, if previously set by SetName. 199 static const char* GetName(); 200 201 // Creates a new thread. The `stack_size` parameter can be 0 to indicate 202 // that the default stack size should be used. Upon success, 203 // `*thread_handle` will be assigned a handle to the newly created thread, 204 // and `delegate`'s ThreadMain method will be executed on the newly created 205 // thread. 206 // NOTE: When you are done with the thread handle, you must call Join to 207 // release system resources associated with the thread. You must ensure that 208 // the Delegate object outlives the thread. Create(size_t stack_size,Delegate * delegate,PlatformThreadHandle * thread_handle)209 static bool Create(size_t stack_size, 210 Delegate* delegate, 211 PlatformThreadHandle* thread_handle) { 212 return CreateWithType(stack_size, delegate, thread_handle, 213 ThreadType::kDefault); 214 } 215 216 // CreateWithType() does the same thing as Create() except the priority and 217 // possibly the QoS of the thread is set based on `thread_type`. 218 // `pump_type_hint` must be provided if the thread will be using a 219 // MessagePumpForUI or MessagePumpForIO as this affects the application of 220 // `thread_type`. 221 static bool CreateWithType( 222 size_t stack_size, 223 Delegate* delegate, 224 PlatformThreadHandle* thread_handle, 225 ThreadType thread_type, 226 MessagePumpType pump_type_hint = MessagePumpType::DEFAULT); 227 228 // CreateNonJoinable() does the same thing as Create() except the thread 229 // cannot be Join()'d. Therefore, it also does not output a 230 // PlatformThreadHandle. 231 static bool CreateNonJoinable(size_t stack_size, Delegate* delegate); 232 233 // CreateNonJoinableWithType() does the same thing as CreateNonJoinable() 234 // except the type of the thread is set based on `type`. `pump_type_hint` must 235 // be provided if the thread will be using a MessagePumpForUI or 236 // MessagePumpForIO as this affects the application of `thread_type`. 237 static bool CreateNonJoinableWithType( 238 size_t stack_size, 239 Delegate* delegate, 240 ThreadType thread_type, 241 MessagePumpType pump_type_hint = MessagePumpType::DEFAULT); 242 243 // Joins with a thread created via the Create function. This function blocks 244 // the caller until the designated thread exits. This will invalidate 245 // `thread_handle`. 246 static void Join(PlatformThreadHandle thread_handle); 247 248 // Detaches and releases the thread handle. The thread is no longer joinable 249 // and `thread_handle` is invalidated after this call. 250 static void Detach(PlatformThreadHandle thread_handle); 251 252 // Returns true if SetCurrentThreadType() should be able to change the type 253 // of a thread in current process from `from` to `to`. 254 static bool CanChangeThreadType(ThreadType from, ThreadType to); 255 256 // Declares the type of work running on the current thread. This will affect 257 // things like thread priority and thread QoS (Quality of Service) to the best 258 // of the current platform's abilities. 259 static void SetCurrentThreadType(ThreadType thread_type); 260 261 // Get the last `thread_type` set by SetCurrentThreadType, no matter if the 262 // underlying priority successfully changed or not. 263 static ThreadType GetCurrentThreadType(); 264 265 // Returns a realtime period provided by `delegate`. 266 static TimeDelta GetRealtimePeriod(Delegate* delegate); 267 268 // Returns the override of task leeway if any. 269 static std::optional<TimeDelta> GetThreadLeewayOverride(); 270 271 // Returns the default thread stack size set by chrome. If we do not 272 // explicitly set default size then returns 0. 273 static size_t GetDefaultThreadStackSize(); 274 275 static ThreadPriorityForTest GetCurrentThreadPriorityForTest(); 276 277 protected: 278 static void SetNameCommon(const std::string& name); 279 }; 280 281 #if BUILDFLAG(IS_APPLE) 282 class BASE_EXPORT PlatformThreadApple : public PlatformThreadBase { 283 public: 284 // Stores the period value in TLS. 285 static void SetCurrentThreadRealtimePeriodValue(TimeDelta realtime_period); 286 287 static TimeDelta GetCurrentThreadRealtimePeriodForTest(); 288 289 // Initializes features for this class. See `base::features::Init()`. 290 static void InitializeFeatures(); 291 }; 292 #endif // BUILDFLAG(IS_APPLE) 293 294 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 295 class ThreadTypeDelegate; 296 using IsViaIPC = base::StrongAlias<class IsViaIPCTag, bool>; 297 298 class BASE_EXPORT PlatformThreadLinux : public PlatformThreadBase { 299 public: 300 static constexpr struct sched_param kRealTimeAudioPrio = {8}; 301 static constexpr struct sched_param kRealTimeDisplayPrio = {6}; 302 303 // Sets a delegate which handles thread type changes for this process. This 304 // must be externally synchronized with any call to SetCurrentThreadType. 305 static void SetThreadTypeDelegate(ThreadTypeDelegate* delegate); 306 307 // Toggles a specific thread's type at runtime. This can be used to 308 // change the priority of a thread in a different process and will fail 309 // if the calling process does not have proper permissions. The 310 // SetCurrentThreadType() function above is preferred in favor of 311 // security but on platforms where sandboxed processes are not allowed to 312 // change priority this function exists to allow a non-sandboxed process 313 // to change the priority of sandboxed threads for improved performance. 314 // Warning: Don't use this for a main thread because that will change the 315 // whole thread group's (i.e. process) priority. 316 static void SetThreadType(PlatformThreadId process_id, 317 PlatformThreadId thread_id, 318 ThreadType thread_type, 319 IsViaIPC via_ipc); 320 321 // For a given thread id and thread type, setup the cpuset and schedtune 322 // CGroups for the thread. 323 static void SetThreadCgroupsForThreadType(PlatformThreadId thread_id, 324 ThreadType thread_type); 325 326 // Determine if thread_id is a background thread by looking up whether 327 // it is in the urgent or non-urgent cpuset 328 static bool IsThreadBackgroundedForTest(PlatformThreadId thread_id); 329 }; 330 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 331 332 #if BUILDFLAG(IS_CHROMEOS) 333 BASE_EXPORT BASE_DECLARE_FEATURE(kSetRtForDisplayThreads); 334 335 class CrossProcessPlatformThreadDelegate; 336 337 class BASE_EXPORT PlatformThreadChromeOS : public PlatformThreadLinux { 338 public: 339 // Sets a delegate which handles thread type changes for threads of another 340 // process. This must be externally synchronized with any call to 341 // SetCurrentThreadType. 342 static void SetCrossProcessPlatformThreadDelegate( 343 CrossProcessPlatformThreadDelegate* delegate); 344 345 // Initializes features for this class. See `base::features::Init()`. 346 static void InitializeFeatures(); 347 348 // Toggles a specific thread's type at runtime. This is the ChromeOS-specific 349 // version and includes Linux's functionality but does slightly more. See 350 // PlatformThreadLinux's SetThreadType() header comment for Linux details. 351 static void SetThreadType(PlatformThreadId process_id, 352 PlatformThreadId thread_id, 353 ThreadType thread_type, 354 IsViaIPC via_ipc); 355 356 // Returns true if the feature for backgrounding of threads is enabled. 357 static bool IsThreadsBgFeatureEnabled(); 358 359 // Returns true if the feature for setting display threads to RT is enabled. 360 static bool IsDisplayThreadsRtFeatureEnabled(); 361 362 // Set a specific thread as backgrounded. This is called when the process 363 // moves to and from the background and changes have to be made to each of its 364 // thread's scheduling attributes. 365 static void SetThreadBackgrounded(ProcessId process_id, 366 PlatformThreadId thread_id, 367 bool backgrounded); 368 369 // Returns the thread type of a thread given its thread id. 370 static std::optional<ThreadType> GetThreadTypeFromThreadId( 371 ProcessId process_id, 372 PlatformThreadId thread_id); 373 374 // DCHECKs that the caller is on the correct sequence to perform cross-process 375 // priority changes without races. 376 // 377 // This does not simply return a `SequenceChecker&` and let the caller do the 378 // check, because doing so requires an `#include` of sequence_checker.h (since 379 // `SequenceChecker` is an alias rather than a forward-declarable class), 380 // which complicates life for other base/ headers trying to avoid circular 381 // dependencies. 382 static void DcheckCrossProcessThreadPrioritySequence(); 383 }; 384 #endif // BUILDFLAG(IS_CHROMEOS) 385 386 // Alias to the correct platform-specific class based on preprocessor directives 387 #if BUILDFLAG(IS_APPLE) 388 using PlatformThread = PlatformThreadApple; 389 #elif BUILDFLAG(IS_CHROMEOS) 390 using PlatformThread = PlatformThreadChromeOS; 391 #elif BUILDFLAG(IS_LINUX) 392 using PlatformThread = PlatformThreadLinux; 393 #else 394 using PlatformThread = PlatformThreadBase; 395 #endif 396 397 namespace internal { 398 399 void SetCurrentThreadType(ThreadType thread_type, 400 MessagePumpType pump_type_hint); 401 402 void SetCurrentThreadTypeImpl(ThreadType thread_type, 403 MessagePumpType pump_type_hint); 404 405 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 406 void SetThreadTypeLinux(PlatformThreadId process_id, 407 PlatformThreadId thread_id, 408 ThreadType thread_type, 409 IsViaIPC via_ipc); 410 #endif 411 #if BUILDFLAG(IS_CHROMEOS) 412 void SetThreadTypeChromeOS(PlatformThreadId process_id, 413 PlatformThreadId thread_id, 414 ThreadType thread_type, 415 IsViaIPC via_ipc); 416 #endif 417 #if BUILDFLAG(IS_CHROMEOS) 418 inline constexpr auto SetThreadType = SetThreadTypeChromeOS; 419 #elif BUILDFLAG(IS_LINUX) 420 inline constexpr auto SetThreadType = SetThreadTypeLinux; 421 #endif 422 423 } // namespace internal 424 425 } // namespace base 426 427 #endif // BASE_THREADING_PLATFORM_THREAD_H_ 428