1 // Copyright 2016 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 #ifndef BASE_TASK_THREAD_POOL_WORKER_THREAD_H_ 6 #define BASE_TASK_THREAD_POOL_WORKER_THREAD_H_ 7 8 #include "base/base_export.h" 9 #include "base/compiler_specific.h" 10 #include "base/memory/raw_ptr.h" 11 #include "base/memory/ref_counted.h" 12 #include "base/synchronization/atomic_flag.h" 13 #include "base/synchronization/waitable_event.h" 14 #include "base/task/common/checked_lock.h" 15 #include "base/task/thread_pool/task_source.h" 16 #include "base/task/thread_pool/task_tracker.h" 17 #include "base/task/thread_pool/tracked_ref.h" 18 #include "base/thread_annotations.h" 19 #include "base/threading/platform_thread.h" 20 #include "base/time/time.h" 21 #include "build/build_config.h" 22 23 namespace base { 24 25 class WorkerThreadObserver; 26 27 namespace internal { 28 29 class TaskTracker; 30 31 // A worker that manages a single thread to run Tasks from TaskSources returned 32 // by a delegate. 33 // 34 // A WorkerThread starts out sleeping. It is woken up by a call to WakeUp(). 35 // After a wake-up, a WorkerThread runs Tasks from TaskSources returned by 36 // the GetWork() method of its delegate as long as it doesn't return nullptr. It 37 // also periodically checks with its TaskTracker whether shutdown has completed 38 // and exits when it has. 39 // 40 // This class is thread-safe. 41 class BASE_EXPORT WorkerThread : public RefCountedThreadSafe<WorkerThread>, 42 public PlatformThread::Delegate { 43 public: 44 // Labels this WorkerThread's association. This doesn't affect any logic 45 // but will add a stack frame labeling this thread for ease of stack trace 46 // identification 47 enum class ThreadLabel { 48 POOLED, 49 SHARED, 50 DEDICATED, 51 #if BUILDFLAG(IS_WIN) 52 SHARED_COM, 53 DEDICATED_COM, 54 #endif // BUILDFLAG(IS_WIN) 55 }; 56 57 // Delegate interface for WorkerThread. All methods are called from the 58 // thread managed by the WorkerThread instance. 59 class BASE_EXPORT Delegate { 60 public: 61 virtual ~Delegate() = default; 62 63 // Returns the ThreadLabel the Delegate wants its WorkerThreads' stacks 64 // to be labeled with. 65 virtual ThreadLabel GetThreadLabel() const = 0; 66 67 // Called by |worker|'s thread when it enters its main function. 68 virtual void OnMainEntry(WorkerThread* worker) = 0; 69 70 // Called by |worker|'s thread to get a TaskSource from which to run a Task. 71 virtual RegisteredTaskSource GetWork(WorkerThread* worker) = 0; 72 73 // Called by the worker thread to swap the task source that has just run for 74 // another one, if available. |task_source| must not be null. The worker can 75 // then run the task returned as if it was acquired via GetWork(). 76 virtual RegisteredTaskSource SwapProcessedTask( 77 RegisteredTaskSource task_source, 78 WorkerThread* worker) = 0; 79 80 // Called to determine how long to sleep before the next call to GetWork(). 81 // GetWork() may be called before this timeout expires if the worker's 82 // WakeUp() method is called. 83 virtual TimeDelta GetSleepTimeout() = 0; 84 85 // Called by the WorkerThread's thread to wait for work. 86 virtual void WaitForWork(); 87 88 // Called by |worker|'s thread right before the main function exits. The 89 // Delegate is free to release any associated resources in this call. It is 90 // guaranteed that WorkerThread won't access the Delegate or the 91 // TaskTracker after calling OnMainExit() on the Delegate. OnMainExit(WorkerThread * worker)92 virtual void OnMainExit(WorkerThread* worker) {} 93 94 // Called by a WorkerThread when it is woken up without any work being 95 // available for it to run. RecordUnnecessaryWakeup()96 virtual void RecordUnnecessaryWakeup() {} 97 98 static constexpr TimeDelta kPurgeThreadCacheIdleDelay = Seconds(1); 99 100 protected: 101 friend WorkerThread; 102 static bool IsDelayFirstWorkerSleepEnabled(); 103 104 // Called in WaitForWork() to hide the worker's synchronization 105 // mechanism. Returns |true| if signaled, and |false| if the call timed out. 106 virtual bool TimedWait(TimeDelta timeout) = 0; 107 108 #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ 109 PA_CONFIG(THREAD_CACHE_SUPPORTED) 110 // Returns the desired sleep time before the worker has to wake up to purge 111 // the cache thread or reclaim itself. |min_sleep_time| contains the minimal 112 // acceptable amount of time to sleep. 113 static TimeDelta GetSleepTimeBeforePurge(TimeDelta min_sleep_time); 114 #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && 115 // PA_CONFIG(THREAD_CACHE_SUPPORTED) 116 }; 117 118 // Creates a WorkerThread that runs Tasks from TaskSources returned by 119 // |delegate()|. No actual thread will be created for this WorkerThread before 120 // Start() is called. |thread_type_hint| is the preferred thread type; the 121 // actual thread type depends on shutdown state and platform 122 // capabilities. |task_tracker| is used to handle shutdown behavior of 123 // Tasks. |sequence_num| is an index that helps identifying this 124 // WorkerThread. |predecessor_lock| is a lock that is allowed to be held when 125 // calling methods on this WorkerThread. Either JoinForTesting() or Cleanup() 126 // must be called before releasing the last external reference. 127 WorkerThread(ThreadType thread_type_hint, 128 TrackedRef<TaskTracker> task_tracker, 129 size_t sequence_num, 130 const CheckedLock* predecessor_lock = nullptr); 131 132 WorkerThread(const WorkerThread&) = delete; 133 WorkerThread& operator=(const WorkerThread&) = delete; 134 135 // Creates a thread to back the WorkerThread. The thread will be in a wait 136 // state pending a WakeUp() call. No thread will be created if Cleanup() was 137 // called. `io_thread_task_runner` is used to setup FileDescriptorWatcher on 138 // worker threads. `io_thread_task_runner` must refer to a Thread with 139 // MessgaePumpType::IO. If specified, |worker_thread_observer| will be 140 // notified when the worker enters and exits its main function. It must not be 141 // destroyed before JoinForTesting() has returned (must never be destroyed in 142 // production). Returns true on success. 143 bool Start(scoped_refptr<SingleThreadTaskRunner> io_thread_task_runner_, 144 WorkerThreadObserver* worker_thread_observer = nullptr); 145 146 147 148 // Joins this WorkerThread. If a Task is already running, it will be 149 // allowed to complete its execution. This can only be called once. 150 // 151 // Note: A thread that detaches before JoinForTesting() is called may still be 152 // running after JoinForTesting() returns. However, it can't run tasks after 153 // JoinForTesting() returns. 154 virtual void JoinForTesting() = 0; 155 156 // Returns true if the worker is alive. 157 bool ThreadAliveForTesting() const; 158 159 // Makes a request to cleanup the worker. This may be called from any thread. 160 // The caller is expected to release its reference to this object after 161 // calling Cleanup(). Further method calls after Cleanup() returns are 162 // undefined. 163 // 164 // Expected Usage: 165 // scoped_refptr<WorkerThread> worker_ = /* Existing Worker */ 166 // worker_->Cleanup(); 167 // worker_ = nullptr; 168 virtual void Cleanup() = 0; 169 170 virtual Delegate* delegate() = 0; 171 172 // Possibly updates the thread type to the appropriate type based on the 173 // thread type hint, current shutdown state, and platform capabilities. 174 // Must be called on the thread managed by |this|. 175 void MaybeUpdateThreadType(); 176 177 // Informs this WorkerThread about periods during which it is not being 178 // used. Thread-safe. 179 void BeginUnusedPeriod(); 180 void EndUnusedPeriod(); 181 // Returns the last time this WorkerThread was used. Returns a null time if 182 // this WorkerThread is currently in-use. Thread-safe. 183 TimeTicks GetLastUsedTime() const; 184 sequence_num()185 size_t sequence_num() const { return sequence_num_; } 186 187 protected: 188 friend class RefCountedThreadSafe<WorkerThread>; 189 class Thread; 190 191 ~WorkerThread() override; 192 193 bool ShouldExit() const; 194 195 // Returns the thread type to use based on the thread type hint, current 196 // shutdown state, and platform capabilities. 197 ThreadType GetDesiredThreadType() const; 198 199 // Changes the thread type to |desired_thread_type|. Must be called on the 200 // thread managed by |this|. 201 void UpdateThreadType(ThreadType desired_thread_type); 202 203 // PlatformThread::Delegate: 204 void ThreadMain() override; 205 206 // Dummy frames to act as "RunLabeledWorker()" (see RunMain() below). Their 207 // impl is aliased to prevent compiler/linker from optimizing them out. 208 void RunPooledWorker(); 209 void RunBackgroundPooledWorker(); 210 void RunSharedWorker(); 211 void RunBackgroundSharedWorker(); 212 void RunDedicatedWorker(); 213 void RunBackgroundDedicatedWorker(); 214 #if BUILDFLAG(IS_WIN) 215 void RunSharedCOMWorker(); 216 void RunBackgroundSharedCOMWorker(); 217 void RunDedicatedCOMWorker(); 218 void RunBackgroundDedicatedCOMWorker(); 219 #endif // BUILDFLAG(IS_WIN) 220 221 // The real main, invoked through : 222 // ThreadMain() -> RunLabeledWorker() -> RunWorker(). 223 // "RunLabeledWorker()" is a dummy frame based on ThreadLabel+ThreadType 224 // and used to easily identify threads in stack traces. 225 NOT_TAIL_CALLED void RunWorker(); 226 227 // Self-reference to prevent destruction of |this| while the thread is alive. 228 // Set in Start() before creating the thread. Reset in ThreadMain() before the 229 // thread exits. No lock required because the first access occurs before the 230 // thread is created and the second access occurs on the thread. 231 scoped_refptr<WorkerThread> self_; 232 233 mutable CheckedLock thread_lock_; 234 235 // Handle for the thread managed by |this|. 236 PlatformThreadHandle thread_handle_ GUARDED_BY(thread_lock_); 237 238 // The last time this worker was used by its owner (e.g. to process work or 239 // stand as a required idle thread). 240 TimeTicks last_used_time_ GUARDED_BY(thread_lock_); 241 242 // Whether the thread should exit. Set by Cleanup(). 243 AtomicFlag should_exit_; 244 245 const TrackedRef<TaskTracker> task_tracker_; 246 247 // Optional observer notified when a worker enters and exits its main 248 // function. Set in Start() and never modified afterwards. 249 raw_ptr<WorkerThreadObserver> worker_thread_observer_ = nullptr; 250 251 // Desired thread type. 252 const ThreadType thread_type_hint_; 253 254 // Actual thread type. Can be different than |thread_type_hint_| 255 // depending on system capabilities and shutdown state. No lock required 256 // because all post-construction accesses occur on the thread. 257 ThreadType current_thread_type_; 258 259 // Set once JoinForTesting() has been called. 260 AtomicFlag join_called_for_testing_; 261 262 const size_t sequence_num_; 263 264 // Service thread task runner. 265 scoped_refptr<SingleThreadTaskRunner> io_thread_task_runner_; 266 }; 267 268 } // namespace internal 269 } // namespace base 270 271 #endif // BASE_TASK_THREAD_POOL_WORKER_THREAD_H_ 272