• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 BeginRestrictedTasks() override;
80   void EndRestrictedTasks() override;
81   void BeginFizzlingBlockShutdownTasks() override;
82   void EndFizzlingBlockShutdownTasks() override;
83 
84   // PooledTaskRunnerDelegate:
85   bool EnqueueJobTaskSource(scoped_refptr<JobTaskSource> task_source) override;
86   void RemoveJobTaskSource(scoped_refptr<JobTaskSource> task_source) override;
87   void UpdatePriority(scoped_refptr<TaskSource> task_source,
88                       TaskPriority priority) override;
89   void UpdateJobPriority(scoped_refptr<TaskSource> task_source,
90                          TaskPriority priority) override;
91 
92   // Returns the TimeTicks of the next task scheduled on ThreadPool (Now() if
93   // immediate, nullopt if none). This is thread-safe, i.e., it's safe if tasks
94   // are being posted in parallel with this call but such a situation obviously
95   // results in a race as to whether this call will see the new tasks in time.
96   std::optional<TimeTicks> NextScheduledRunTimeForTesting() const;
97 
98   // Forces ripe delayed tasks to be posted (e.g. when time is mocked and
99   // advances faster than the real-time delay on ServiceThread).
100   void ProcessRipeDelayedTasksForTesting();
101 
102   // Requests that all threads started by future ThreadPoolImpls in this process
103   // have a synchronous start (if |enabled|; cancels this behavior otherwise).
104   // Must be called while no ThreadPoolImpls are alive in this process. This is
105   // exposed here on this internal API rather than as a ThreadPoolInstance
106   // configuration param because only one internal test truly needs this.
107   static void SetSynchronousThreadStartForTesting(bool enabled);
108 
109   // Posts |task| with a |delay| and specific |traits|. |delay| can be zero. For
110   // one off tasks that don't require a TaskRunner. Returns false if the task
111   // definitely won't run because of current shutdown state.
112   bool PostDelayedTask(const Location& from_here,
113                        const TaskTraits& traits,
114                        OnceClosure task,
115                        TimeDelta delay);
116 
117   // Returns a TaskRunner whose PostTask invocations result in scheduling tasks
118   // using |traits|. Tasks may run in any order and in parallel.
119   scoped_refptr<TaskRunner> CreateTaskRunner(const TaskTraits& traits);
120 
121   // Returns a SequencedTaskRunner whose PostTask invocations result in
122   // scheduling tasks using |traits|. Tasks run one at a time in posting order.
123   scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunner(
124       const TaskTraits& traits);
125 
126   // Returns a SingleThreadTaskRunner whose PostTask invocations result in
127   // scheduling tasks using |traits|. Tasks run on a single thread in posting
128   // order. If |traits| identifies an existing thread,
129   // SingleThreadTaskRunnerThreadMode::SHARED must be used.
130   scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunner(
131       const TaskTraits& traits,
132       SingleThreadTaskRunnerThreadMode thread_mode);
133 
134 #if BUILDFLAG(IS_WIN)
135   // Returns a SingleThreadTaskRunner whose PostTask invocations result in
136   // scheduling tasks using |traits| in a COM Single-Threaded Apartment. Tasks
137   // run in the same Single-Threaded Apartment in posting order for the returned
138   // SingleThreadTaskRunner. If |traits| identifies an existing thread,
139   // SingleThreadTaskRunnerThreadMode::SHARED must be used.
140   scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunner(
141       const TaskTraits& traits,
142       SingleThreadTaskRunnerThreadMode thread_mode);
143 #endif  // BUILDFLAG(IS_WIN)
144 
145   // Returns a task runner whose PostTask invocations result in scheduling tasks
146   // using |traits|. The priority in |traits| can be updated at any time via
147   // UpdateableSequencedTaskRunner::UpdatePriority(). An update affects all
148   // tasks posted to the task runner that aren't running yet. Tasks run one at a
149   // time in posting order.
150   //
151   // |traits| requirements:
152   // - base::ThreadPolicy must be specified if the priority of the task runner
153   //   will ever be increased from BEST_EFFORT.
154   scoped_refptr<UpdateableSequencedTaskRunner>
155   CreateUpdateableSequencedTaskRunner(const TaskTraits& traits);
156 
157  private:
158   // Invoked after |num_fences_| or |num_best_effort_fences_| is updated. Sets
159   // the CanRunPolicy in TaskTracker and wakes up workers as appropriate.
160   void UpdateCanRunPolicy();
161 
162   const ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) const;
163 
164   // ThreadGroup::Delegate:
165   ThreadGroup* GetThreadGroupForTraits(const TaskTraits& traits) override;
166 
167   // Posts |task| to be executed by the appropriate thread group as part of
168   // |sequence|. This must only be called after |task| has gone through
169   // TaskTracker::WillPostTask() and after |task|'s delayed run time.
170   bool PostTaskWithSequenceNow(Task task, scoped_refptr<Sequence> sequence);
171 
172   // PooledTaskRunnerDelegate:
173   bool PostTaskWithSequence(Task task,
174                             scoped_refptr<Sequence> sequence) override;
175   bool ShouldYield(const TaskSource* task_source) override;
176 
177   const std::string histogram_label_;
178   const std::unique_ptr<TaskTrackerImpl> task_tracker_;
179   const bool use_background_threads_;
180   ServiceThread service_thread_;
181   DelayedTaskManager delayed_task_manager_;
182   PooledSingleThreadTaskRunnerManager single_thread_task_runner_manager_;
183 
184   std::unique_ptr<ThreadGroup> foreground_thread_group_;
185   std::unique_ptr<ThreadGroup> utility_thread_group_;
186   std::unique_ptr<ThreadGroup> background_thread_group_;
187 
188   // Whether this TaskScheduler was started.
189   bool started_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
190 
191   // Whether the --disable-best-effort-tasks switch is preventing execution of
192   // BEST_EFFORT tasks until shutdown.
193   const bool has_disable_best_effort_switch_;
194 
195   // Number of fences preventing execution of tasks of any/BEST_EFFORT priority.
196   int num_fences_ GUARDED_BY_CONTEXT(sequence_checker_) = 0;
197   int num_best_effort_fences_ GUARDED_BY_CONTEXT(sequence_checker_) = 0;
198 
199 #if DCHECK_IS_ON()
200   // Set once JoinForTesting() has returned.
201   AtomicFlag join_for_testing_returned_;
202 #endif
203 
204 #if BUILDFLAG(IS_WIN) && defined(COM_INIT_CHECK_HOOK_ENABLED)
205   // Provides COM initialization verification for supported builds.
206   base::win::ComInitCheckHook com_init_check_hook_;
207 #endif
208 
209   // Asserts that operations occur in sequence with Start().
210   SEQUENCE_CHECKER(sequence_checker_);
211 
212   TrackedRefFactory<ThreadGroup::Delegate> tracked_ref_factory_;
213 };
214 
215 }  // namespace internal
216 }  // namespace base
217 
218 #endif  // BASE_TASK_THREAD_POOL_THREAD_POOL_IMPL_H_
219