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