blob: 56393ab2e4f2c36a51aaa5b3bad807affb262073 [file] [log] [blame]
fdoray67ecfb52016-05-02 14:49:031// Copyright 2016 The Chromium Authors. All rights reserved.
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_SCHEDULER_TASK_SCHEDULER_H_
6#define BASE_TASK_SCHEDULER_TASK_SCHEDULER_H_
7
8#include <memory>
robliaod2ab1f72016-08-02 20:51:499#include <vector>
fdoray67ecfb52016-05-02 14:49:0310
11#include "base/base_export.h"
tzik070c8ffb2017-03-29 05:28:1212#include "base/callback.h"
Francois Doray6d3c649692017-06-16 19:20:2513#include "base/gtest_prod_util.h"
fdoray67ecfb52016-05-02 14:49:0314#include "base/memory/ref_counted.h"
fdoraye72adfa12016-11-02 14:35:2615#include "base/sequenced_task_runner.h"
16#include "base/single_thread_task_runner.h"
fdoray5d16e802017-04-19 14:45:1617#include "base/strings/string_piece.h"
fdoray67ecfb52016-05-02 14:49:0318#include "base/task_runner.h"
fdoray3f6f57a42017-03-28 18:02:3919#include "base/task_scheduler/scheduler_worker_pool_params.h"
robliao94520d72017-05-12 12:43:3520#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
fdoray67ecfb52016-05-02 14:49:0321#include "base/task_scheduler/task_traits.h"
fdoray45cc90792017-01-05 19:24:3122#include "base/time/time.h"
robliao75dd50b2017-03-29 17:11:1723#include "build/build_config.h"
fdoray67ecfb52016-05-02 14:49:0324
fdoray1028b07d2017-01-31 20:36:1425namespace gin {
Andreas Haasc13cae82017-11-16 12:54:3826class V8BackgroundTaskRunner;
fdoray1028b07d2017-01-31 20:36:1427}
28
Francois Doray6d3c649692017-06-16 19:20:2529namespace content {
30// Can't use the FRIEND_TEST_ALL_PREFIXES macro because the test is in a
31// different namespace.
32class BrowserMainLoopTest_CreateThreadsInSingleProcess_Test;
33} // namespace content
34
fdoray67ecfb52016-05-02 14:49:0335namespace base {
36
robliao6f59a9a2016-10-20 17:26:1437class HistogramBase;
Brett Wilsonabbb9602017-09-11 23:26:3938class Location;
robliaod2ab1f72016-08-02 20:51:4939
fdoray67ecfb52016-05-02 14:49:0340// Interface for a task scheduler and static methods to manage the instance used
fdoray0f358ee2017-04-25 21:22:2341// by the post_task.h API.
42//
43// The task scheduler doesn't create threads until Start() is called. Tasks can
44// be posted at any time but will not run until after Start() is called.
45//
46// The instance methods of this class are thread-safe.
47//
48// Note: All base/task_scheduler users should go through post_task.h instead of
49// TaskScheduler except for the one callsite per process which manages the
50// process's instance.
fdoray67ecfb52016-05-02 14:49:0351class BASE_EXPORT TaskScheduler {
52 public:
fdoray3f6f57a42017-03-28 18:02:3953 struct BASE_EXPORT InitParams {
Robert Liao4393dc62017-11-01 20:06:0354 enum class SharedWorkerPoolEnvironment {
55 // Use the default environment (no environment).
56 DEFAULT,
57#if defined(OS_WIN)
58 // Place the worker in a COM MTA.
59 COM_MTA,
60#endif // defined(OS_WIN)
61 };
62
fdoray3f6f57a42017-03-28 18:02:3963 InitParams(
64 const SchedulerWorkerPoolParams& background_worker_pool_params_in,
65 const SchedulerWorkerPoolParams&
66 background_blocking_worker_pool_params_in,
67 const SchedulerWorkerPoolParams& foreground_worker_pool_params_in,
68 const SchedulerWorkerPoolParams&
Robert Liao4393dc62017-11-01 20:06:0369 foreground_blocking_worker_pool_params_in,
70 SharedWorkerPoolEnvironment shared_worker_pool_environment_in =
71 SharedWorkerPoolEnvironment::DEFAULT);
fdoray3f6f57a42017-03-28 18:02:3972 ~InitParams();
73
Francois Doray6d3c649692017-06-16 19:20:2574 SchedulerWorkerPoolParams background_worker_pool_params;
75 SchedulerWorkerPoolParams background_blocking_worker_pool_params;
76 SchedulerWorkerPoolParams foreground_worker_pool_params;
77 SchedulerWorkerPoolParams foreground_blocking_worker_pool_params;
Robert Liao4393dc62017-11-01 20:06:0378 SharedWorkerPoolEnvironment shared_worker_pool_environment;
fdoray3f6f57a42017-03-28 18:02:3979 };
80
fdoray7bba05e2017-01-25 02:34:4581 // Destroying a TaskScheduler is not allowed in production; it is always
82 // leaked. In tests, it should only be destroyed after JoinForTesting() has
83 // returned.
fdoray67ecfb52016-05-02 14:49:0384 virtual ~TaskScheduler() = default;
85
fdoray0f358ee2017-04-25 21:22:2386 // Allows the task scheduler to create threads and run tasks following the
87 // |init_params| specification. CHECKs on failure.
88 virtual void Start(const InitParams& init_params) = 0;
89
fdoray45cc90792017-01-05 19:24:3190 // Posts |task| with a |delay| and specific |traits|. |delay| can be zero.
fdoray67ecfb52016-05-02 14:49:0391 // For one off tasks that don't require a TaskRunner.
Brett Wilsonabbb9602017-09-11 23:26:3992 virtual void PostDelayedTaskWithTraits(const Location& from_here,
93 const TaskTraits& traits,
94 OnceClosure task,
95 TimeDelta delay) = 0;
fdoray67ecfb52016-05-02 14:49:0396
fdoraye72adfa12016-11-02 14:35:2697 // Returns a TaskRunner whose PostTask invocations result in scheduling tasks
98 // using |traits|. Tasks may run in any order and in parallel.
fdoray67ecfb52016-05-02 14:49:0399 virtual scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(
fdoraye72adfa12016-11-02 14:35:26100 const TaskTraits& traits) = 0;
101
102 // Returns a SequencedTaskRunner whose PostTask invocations result in
103 // scheduling tasks using |traits|. Tasks run one at a time in posting order.
104 virtual scoped_refptr<SequencedTaskRunner>
105 CreateSequencedTaskRunnerWithTraits(const TaskTraits& traits) = 0;
106
107 // Returns a SingleThreadTaskRunner whose PostTask invocations result in
108 // scheduling tasks using |traits|. Tasks run on a single thread in posting
109 // order.
110 virtual scoped_refptr<SingleThreadTaskRunner>
robliao94520d72017-05-12 12:43:35111 CreateSingleThreadTaskRunnerWithTraits(
112 const TaskTraits& traits,
robliao0c097192017-05-16 13:56:37113 SingleThreadTaskRunnerThreadMode thread_mode) = 0;
fdoray67ecfb52016-05-02 14:49:03114
robliao75dd50b2017-03-29 17:11:17115#if defined(OS_WIN)
116 // Returns a SingleThreadTaskRunner whose PostTask invocations result in
117 // scheduling tasks using |traits| in a COM Single-Threaded Apartment. Tasks
118 // run in the same Single-Threaded Apartment in posting order for the returned
119 // SingleThreadTaskRunner. There is not necessarily a one-to-one
120 // correspondence between SingleThreadTaskRunners and Single-Threaded
121 // Apartments. The implementation is free to share apartments or create new
122 // apartments as necessary. In either case, care should be taken to make sure
123 // COM pointers are not smuggled across apartments.
124 virtual scoped_refptr<SingleThreadTaskRunner>
robliao94520d72017-05-12 12:43:35125 CreateCOMSTATaskRunnerWithTraits(
126 const TaskTraits& traits,
robliao0c097192017-05-16 13:56:37127 SingleThreadTaskRunnerThreadMode thread_mode) = 0;
robliao75dd50b2017-03-29 17:11:17128#endif // defined(OS_WIN)
129
robliao6f59a9a2016-10-20 17:26:14130 // Returns a vector of all histograms available in this task scheduler.
131 virtual std::vector<const HistogramBase*> GetHistograms() const = 0;
132
fdoray67ecfb52016-05-02 14:49:03133 // Synchronously shuts down the scheduler. Once this is called, only tasks
134 // posted with the BLOCK_SHUTDOWN behavior will be run. When this returns:
135 // - All SKIP_ON_SHUTDOWN tasks that were already running have completed their
136 // execution.
137 // - All posted BLOCK_SHUTDOWN tasks have completed their execution.
138 // - CONTINUE_ON_SHUTDOWN tasks might still be running.
139 // Note that an implementation can keep threads and other resources alive to
140 // support running CONTINUE_ON_SHUTDOWN after this returns. This can only be
141 // called once.
142 virtual void Shutdown() = 0;
143
fdorayfe309b02016-09-26 16:18:58144 // Waits until there are no pending undelayed tasks. May be called in tests
145 // to validate that a condition is met after all undelayed tasks have run.
146 //
147 // Does not wait for delayed tasks. Waits for undelayed tasks posted from
148 // other threads during the call. Returns immediately when shutdown completes.
149 virtual void FlushForTesting() = 0;
150
fdoray7bba05e2017-01-25 02:34:45151 // Joins all threads. Tasks that are already running are allowed to complete
robliaodc6f6212017-02-01 23:13:41152 // their execution. This can only be called once. Using this task scheduler
153 // instance to create task runners or post tasks is not permitted during or
154 // after this call.
fdoray7bba05e2017-01-25 02:34:45155 virtual void JoinForTesting() = 0;
156
fdoray43ec6df2017-04-25 23:16:12157// CreateAndStartWithDefaultParams(), Create(), and SetInstance() register a
158// TaskScheduler to handle tasks posted through the post_task.h API for this
159// process.
160//
161// Processes that need to initialize TaskScheduler with custom params or that
162// need to allow tasks to be posted before the TaskScheduler creates its
163// threads should use Create() followed by Start(). Other processes can use
164// CreateAndStartWithDefaultParams().
165//
166// A registered TaskScheduler is only deleted when a new TaskScheduler is
167// registered. The last registered TaskScheduler is leaked on shutdown. The
168// methods below must not be called when TaskRunners created by a previous
169// TaskScheduler are still alive. The methods are not thread-safe; proper
170// synchronization is required to use the post_task.h API after registering a
171// new TaskScheduler.
robliaod2ab1f72016-08-02 20:51:49172
fdoraydafc3412017-03-21 17:19:29173#if !defined(OS_NACL)
fdoray43ec6df2017-04-25 23:16:12174 // Creates and starts a task scheduler using default params. |name| is used to
fdoraydafc3412017-03-21 17:19:29175 // label threads and histograms. It should identify the component that calls
fdoray43ec6df2017-04-25 23:16:12176 // this. Start() is called by this method; it is invalid to call it again
177 // afterwards. CHECKs on failure. For tests, prefer
178 // base::test::ScopedTaskEnvironment (ensures isolation).
179 static void CreateAndStartWithDefaultParams(StringPiece name);
Gabriel Charette3a32d462017-09-21 02:26:13180
181 // Same as CreateAndStartWithDefaultParams() but allows callers to split the
182 // Create() and StartWithDefaultParams() calls.
183 void StartWithDefaultParams();
fdoraydafc3412017-03-21 17:19:29184#endif // !defined(OS_NACL)
fdoray9c7db3712016-11-18 17:10:53185
fdoray43ec6df2017-04-25 23:16:12186 // Creates a ready to start task scheduler. |name| is used to label threads
187 // and histograms. It should identify the component that creates the
188 // TaskScheduler. The task scheduler doesn't create threads until Start() is
189 // called. Tasks can be posted at any time but will not run until after
190 // Start() is called. For tests, prefer base::test::ScopedTaskEnvironment
fdoray3f6f57a42017-03-28 18:02:39191 // (ensures isolation).
fdoray43ec6df2017-04-25 23:16:12192 static void Create(StringPiece name);
193
fdoray67ecfb52016-05-02 14:49:03194 // Registers |task_scheduler| to handle tasks posted through the post_task.h
Francois Dorayc4c3f642017-08-04 14:56:22195 // API for this process. For tests, prefer base::test::ScopedTaskEnvironment
gab4fe88c1e2017-02-24 18:10:46196 // (ensures isolation).
fdoray67ecfb52016-05-02 14:49:03197 static void SetInstance(std::unique_ptr<TaskScheduler> task_scheduler);
198
gab4fe88c1e2017-02-24 18:10:46199 // Retrieve the TaskScheduler set via SetInstance() or
200 // CreateAndSet(Simple|Default)TaskScheduler(). This should be used very
201 // rarely; most users of TaskScheduler should use the post_task.h API. In
202 // particular, refrain from doing
203 // if (!TaskScheduler::GetInstance()) {
204 // TaskScheduler::SetInstance(...);
205 // base::PostTask(...);
206 // }
207 // instead make sure to SetInstance() early in one determinstic place in the
208 // process' initialization phase.
209 // In doubt, consult with //base/task_scheduler/OWNERS.
fdoray67ecfb52016-05-02 14:49:03210 static TaskScheduler* GetInstance();
fdoray1028b07d2017-01-31 20:36:14211
212 private:
Andreas Haasc13cae82017-11-16 12:54:38213 friend class gin::V8BackgroundTaskRunner;
Francois Doray6d3c649692017-06-16 19:20:25214 friend class content::BrowserMainLoopTest_CreateThreadsInSingleProcess_Test;
fdoray1028b07d2017-01-31 20:36:14215
Jeffrey Hed628419b2017-08-23 18:51:51216 // Returns the maximum number of non-single-threaded non-blocked tasks posted
217 // with |traits| that can run concurrently in this TaskScheduler.
fdoray1028b07d2017-01-31 20:36:14218 //
219 // Do not use this method. To process n items, post n tasks that each process
Jeffrey Hed628419b2017-08-23 18:51:51220 // 1 item rather than GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated()
221 // tasks that each process
222 // n/GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated() items.
fdoray1028b07d2017-01-31 20:36:14223 //
224 // TODO(fdoray): Remove this method. https://crbug.com/687264
Jeffrey Hed628419b2017-08-23 18:51:51225 virtual int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated(
fdoray1028b07d2017-01-31 20:36:14226 const TaskTraits& traits) const = 0;
fdoray67ecfb52016-05-02 14:49:03227};
228
229} // namespace base
230
231#endif // BASE_TASK_SCHEDULER_TASK_SCHEDULER_H_