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_THREAD_POOL_IMPL_H_ 6 #define BASE_TASK_THREAD_POOL_THREAD_POOL_IMPL_H_ 7 8 #include <memory> 9 10 #include "base/base_export.h" 11 #include "base/dcheck_is_on.h" 12 #include "base/functional/callback.h" 13 #include "base/memory/ptr_util.h" 14 #include "base/sequence_checker.h" 15 #include "base/strings/string_piece.h" 16 #include "base/synchronization/atomic_flag.h" 17 #include "base/task/single_thread_task_runner_thread_mode.h" 18 #include "base/task/task_traits.h" 19 #include "base/task/thread_pool/delayed_task_manager.h" 20 #include "base/task/thread_pool/environment_config.h" 21 #include "base/task/thread_pool/pooled_single_thread_task_runner_manager.h" 22 #include "base/task/thread_pool/pooled_task_runner_delegate.h" 23 #include "base/task/thread_pool/service_thread.h" 24 #include "base/task/thread_pool/task_source.h" 25 #include "base/task/thread_pool/task_tracker.h" 26 #include "base/task/thread_pool/thread_group.h" 27 #include "base/task/thread_pool/thread_group_impl.h" 28 #include "base/task/thread_pool/thread_pool_instance.h" 29 #include "base/task/updateable_sequenced_task_runner.h" 30 #include "base/thread_annotations.h" 31 #include "build/build_config.h" 32 #include "third_party/abseil-cpp/absl/types/optional.h" 33 34 #if BUILDFLAG(IS_WIN) 35 #include "base/win/com_init_check_hook.h" 36 #endif 37 38 namespace base { 39 40 namespace internal { 41 42 // Default ThreadPoolInstance implementation. This class is thread-safe, except 43 // for methods noted otherwise in thread_pool_instance.h. 44 class BASE_EXPORT ThreadPoolImpl : public ThreadPoolInstance, 45 public ThreadGroup::Delegate, 46 public PooledTaskRunnerDelegate { 47 public: 48 using TaskTrackerImpl = TaskTracker; 49 50 // Creates a ThreadPoolImpl with a production TaskTracker. |histogram_label| 51 // is used to label histograms. No histograms are recorded if it is empty. 52 explicit ThreadPoolImpl(StringPiece histogram_label); 53 54 // For testing only. Creates a ThreadPoolImpl with a custom TaskTracker. 55 // If |!use_background_threads|, background threads will run with default 56 // priority. 57 ThreadPoolImpl(StringPiece histogram_label, 58 std::unique_ptr<TaskTrackerImpl> task_tracker, 59 bool use_background_threads = true); 60 61 ThreadPoolImpl(const ThreadPoolImpl&) = delete; 62 ThreadPoolImpl& operator=(const ThreadPoolImpl&) = delete; 63 ~ThreadPoolImpl() override; 64 65 // ThreadPoolInstance: 66 void Start(const ThreadPoolInstance::InitParams& init_params, 67 WorkerThreadObserver* worker_thread_observer) override; 68 bool WasStarted() const final; 69 bool WasStartedUnsafe() const final; 70 size_t GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( 71 const TaskTraits& traits) const override; 72 void Shutdown() override; 73 void FlushForTesting() override; 74 void FlushAsyncForTesting(OnceClosure flush_callback) override; 75 void JoinForTesting() override; 76 void BeginFence() override; 77 void EndFence() override; 78 void BeginBestEffortFence() override; 79 void EndBestEffortFence() override; 80 void BeginFizzlingBlockShutdownTasks() override; 81 void EndFizzlingBlockShutdownTasks() override; 82 83 // PooledTaskRunnerDelegate: 84 bool EnqueueJobTaskSource(scoped_refptr<JobTaskSource> task_source) override; 85 void RemoveJobTaskSource(scoped_refptr<JobTaskSource> task_source) override; 86 void UpdatePriority(scoped_refptr<TaskSource> task_source, 87 TaskPriority priority) override; 88 void UpdateJobPriority(scoped_refptr<TaskSource> task_source, 89 TaskPriority priority) override; 90 91 // Returns the TimeTicks of the next task scheduled on ThreadPool (Now() if 92 // immediate, nullopt if none). This is thread-safe, i.e., it's safe if tasks 93 // are being posted in parallel with this call but such a situation obviously 94 // results in a race as to whether this call will see the new tasks in time. 95 absl::optional<TimeTicks> NextScheduledRunTimeForTesting() const; 96 97 // Forces ripe delayed tasks to be posted (e.g. when time is mocked and 98 // advances faster than the real-time delay on ServiceThread). 99 void ProcessRipeDelayedTasksForTesting(); 100 101 // Requests that all threads started by future ThreadPoolImpls in this process 102 // have a synchronous start (if |enabled|; cancels this behavior otherwise). 103 // Must be called while no ThreadPoolImpls are alive in this process. This is 104 // exposed here on this internal API rather than as a ThreadPoolInstance 105 // configuration param because only one internal test truly needs this. 106 static void SetSynchronousThreadStartForTesting(bool enabled); 107 108 // Posts |task| with a |delay| and specific |traits|. |delay| can be zero. For 109 // one off tasks that don't require a TaskRunner. Returns false if the task 110 // definitely won't run because of current shutdown state. 111 bool PostDelayedTask(const Location& from_here, 112 const TaskTraits& traits, 113 OnceClosure task, 114 TimeDelta delay); 115 116 // Returns a TaskRunner whose PostTask invocations result in scheduling tasks 117 // using |traits|. Tasks may run in any order and in parallel. 118 scoped_refptr<TaskRunner> CreateTaskRunner(const TaskTraits& traits); 119 120 // Returns a SequencedTaskRunner whose PostTask invocations result in 121 // scheduling tasks using |traits|. Tasks run one at a time in posting order. 122 scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunner( 123 const TaskTraits& traits); 124 125 // Returns a SingleThreadTaskRunner whose PostTask invocations result in 126 // scheduling tasks using |traits|. Tasks run on a single thread in posting 127 // order. If |traits| identifies an existing thread, 128 // SingleThreadTaskRunnerThreadMode::SHARED must be used. 129 scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunner( 130 const TaskTraits& traits, 131 SingleThreadTaskRunnerThreadMode thread_mode); 132 133 #if BUILDFLAG(IS_WIN) 134 // Returns a SingleThreadTaskRunner whose PostTask invocations result in 135 // scheduling tasks using |traits| in a COM Single-Threaded Apartment. Tasks 136 // run in the same Single-Threaded Apartment in posting order for the returned 137 // SingleThreadTaskRunner. If |traits| identifies an existing thread, 138 // SingleThreadTaskRunnerThreadMode::SHARED must be used. 139 scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunner( 140 const TaskTraits& traits, 141 SingleThreadTaskRunnerThreadMode thread_mode); 142 #endif // BUILDFLAG(IS_WIN) 143 144 // Returns a task runner whose PostTask invocations result in scheduling tasks 145 // using |traits|. The priority in |traits| can be updated at any time via 146 // UpdateableSequencedTaskRunner::UpdatePriority(). An update affects all 147 // tasks posted to the task runner that aren't running yet. Tasks run one at a 148 // time in posting order. 149 // 150 // |traits| requirements: 151 // - base::ThreadPolicy must be specified if the priority of the task runner 152 // will ever be increased from BEST_EFFORT. 153 scoped_refptr<UpdateableSequencedTaskRunner> 154 CreateUpdateableSequencedTaskRunner(const TaskTraits& traits); 155 156 private: 157 // Invoked after |num_fences_| or |num_best_effort_fences_| is updated. Sets 158 // the CanRunPolicy in TaskTracker and wakes up workers as appropriate. 159 void UpdateCanRunPolicy(); 160 161 const ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) const; 162 163 // ThreadGroup::Delegate: 164 ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) override; 165 166 // Posts |task| to be executed by the appropriate thread group as part of 167 // |sequence|. This must only be called after |task| has gone through 168 // TaskTracker::WillPostTask() and after |task|'s delayed run time. 169 bool PostTaskWithSequenceNow(Task task, scoped_refptr<Sequence> sequence); 170 171 // PooledTaskRunnerDelegate: 172 bool PostTaskWithSequence(Task task, 173 scoped_refptr<Sequence> sequence) override; 174 bool ShouldYield(const TaskSource* task_source) override; 175 176 const std::string histogram_label_; 177 const std::unique_ptr<TaskTrackerImpl> task_tracker_; 178 ServiceThread service_thread_; 179 DelayedTaskManager delayed_task_manager_; 180 PooledSingleThreadTaskRunnerManager single_thread_task_runner_manager_; 181 182 std::unique_ptr<ThreadGroup> foreground_thread_group_; 183 std::unique_ptr<ThreadGroup> utility_thread_group_; 184 std::unique_ptr<ThreadGroup> background_thread_group_; 185 186 // Whether this TaskScheduler was started. 187 bool started_ GUARDED_BY_CONTEXT(sequence_checker_) = false; 188 189 // Whether the --disable-best-effort-tasks switch is preventing execution of 190 // BEST_EFFORT tasks until shutdown. 191 const bool has_disable_best_effort_switch_; 192 193 // Number of fences preventing execution of tasks of any/BEST_EFFORT priority. 194 int num_fences_ GUARDED_BY_CONTEXT(sequence_checker_) = 0; 195 int num_best_effort_fences_ GUARDED_BY_CONTEXT(sequence_checker_) = 0; 196 197 #if DCHECK_IS_ON() 198 // Set once JoinForTesting() has returned. 199 AtomicFlag join_for_testing_returned_; 200 #endif 201 202 #if BUILDFLAG(IS_WIN) && defined(COM_INIT_CHECK_HOOK_ENABLED) 203 // Provides COM initialization verification for supported builds. 204 base::win::ComInitCheckHook com_init_check_hook_; 205 #endif 206 207 // Asserts that operations occur in sequence with Start(). 208 SEQUENCE_CHECKER(sequence_checker_); 209 210 TrackedRefFactory<ThreadGroup::Delegate> tracked_ref_factory_; 211 }; 212 213 } // namespace internal 214 } // namespace base 215 216 #endif // BASE_TASK_THREAD_POOL_THREAD_POOL_IMPL_H_ 217