Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 1 | // Copyright 2019 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_THREAD_POOL_H_ |
| 6 | #define BASE_TASK_THREAD_POOL_H_ |
| 7 | |
| 8 | #include <memory> |
| 9 | #include <utility> |
| 10 | |
| 11 | namespace base { |
| 12 | // TODO(gab): thread_pool.h should include task_traits.h but it can't during the |
| 13 | // migration because task_traits.h has to include thread_pool.h to get the old |
| 14 | // base::ThreadPool() trait constructor and that would create a circular |
| 15 | // dependency. Some of the includes below result in an extended version of this |
| 16 | // circular dependency. These forward-declarations are temporarily required for |
| 17 | // the duration of the migration. |
| 18 | enum class TaskPriority : uint8_t; |
| 19 | enum class TaskShutdownBehavior : uint8_t; |
| 20 | enum class ThreadPolicy : uint8_t; |
| 21 | struct MayBlock; |
| 22 | struct WithBaseSyncPrimitives; |
| 23 | class TaskTraits; |
| 24 | // UpdateableSequencedTaskRunner is part of this dance too because |
| 25 | // updateable_sequenced_task_runner.h includes task_traits.h |
| 26 | class UpdateableSequencedTaskRunner; |
| 27 | } // namespace base |
| 28 | |
| 29 | #include "base/base_export.h" |
| 30 | #include "base/bind.h" |
| 31 | #include "base/callback.h" |
| 32 | #include "base/callback_helpers.h" |
| 33 | #include "base/location.h" |
| 34 | #include "base/memory/scoped_refptr.h" |
| 35 | #include "base/post_task_and_reply_with_result_internal.h" |
| 36 | #include "base/sequenced_task_runner.h" |
| 37 | #include "base/single_thread_task_runner.h" |
| 38 | #include "base/task/single_thread_task_runner_thread_mode.h" |
| 39 | #include "base/task_runner.h" |
| 40 | #include "base/time/time.h" |
| 41 | #include "build/build_config.h" |
| 42 | |
| 43 | namespace base { |
| 44 | |
| 45 | // This is the interface to post tasks to base's thread pool. |
| 46 | // |
| 47 | // To post a simple one-off task with default traits: |
| 48 | // base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(...)); |
| 49 | // |
| 50 | // To post a high priority one-off task to respond to a user interaction: |
| 51 | // base::ThreadPool::PostTask( |
| 52 | // FROM_HERE, |
| 53 | // {base::TaskPriority::USER_BLOCKING}, |
| 54 | // base::BindOnce(...)); |
| 55 | // |
| 56 | // To post tasks that must run in sequence with default traits: |
| 57 | // scoped_refptr<SequencedTaskRunner> task_runner = |
| 58 | // base::ThreadPool::CreateSequencedTaskRunner(); |
| 59 | // task_runner->PostTask(FROM_HERE, base::BindOnce(...)); |
| 60 | // task_runner->PostTask(FROM_HERE, base::BindOnce(...)); |
| 61 | // |
| 62 | // To post tasks that may block, must run in sequence and can be skipped on |
| 63 | // shutdown: |
| 64 | // scoped_refptr<SequencedTaskRunner> task_runner = |
| 65 | // base::ThreadPool::CreateSequencedTaskRunner( |
| 66 | // {MayBlock(), TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); |
| 67 | // task_runner->PostTask(FROM_HERE, base::BindOnce(...)); |
| 68 | // task_runner->PostTask(FROM_HERE, base::BindOnce(...)); |
| 69 | // |
| 70 | // The default traits apply to tasks that: |
| 71 | // (1) don't block (ref. MayBlock() and WithBaseSyncPrimitives()), |
| 72 | // (2) prefer inheriting the current priority to specifying their own, and |
| 73 | // (3) can either block shutdown or be skipped on shutdown |
| 74 | // (implementation is free to choose a fitting default). |
| 75 | // Explicit traits must be specified for tasks for which these loose |
| 76 | // requirements are not sufficient. |
| 77 | // |
| 78 | // Prerequisite: A ThreadPoolInstance must have been registered for the current |
| 79 | // process via ThreadPoolInstance::Set() before the API below can be invoked. |
| 80 | // This is typically done during the initialization phase in each process. If |
| 81 | // your code is not running in that phase, you most likely don't have to worry |
| 82 | // about this. You will encounter DCHECKs or nullptr dereferences if this is |
| 83 | // violated. For tests, use base::test::TaskEnvironment. |
| 84 | class BASE_EXPORT ThreadPool { |
| 85 | public: |
| 86 | // base::ThreadPool is meant to be a static API. Do not use this constructor |
| 87 | // in new code! It is a temporary hack to support the old base::ThreadPool() |
| 88 | // trait during the migration to static base::ThreadPool:: APIs. |
| 89 | // Tasks and task runners with this trait will run in the thread pool, |
| 90 | // concurrently with tasks on other task runners. If you need mutual exclusion |
| 91 | // between tasks, see base::ThreadPool::CreateSequencedTaskRunner. |
| 92 | ThreadPool() = default; |
| 93 | |
| 94 | // Equivalent to calling PostTask with default TaskTraits. |
| 95 | static bool PostTask(const Location& from_here, OnceClosure task); |
| 96 | inline static bool PostTask(OnceClosure task, |
| 97 | const Location& from_here = Location::Current()) { |
| 98 | return PostTask(from_here, std::move(task)); |
| 99 | } |
| 100 | |
| 101 | // Equivalent to calling PostDelayedTask with default TaskTraits. |
| 102 | // |
| 103 | // Use PostDelayedTask to specify a BEST_EFFORT priority if the task doesn't |
| 104 | // have to run as soon as |delay| expires. |
| 105 | static bool PostDelayedTask(const Location& from_here, |
| 106 | OnceClosure task, |
| 107 | TimeDelta delay); |
| 108 | |
| 109 | // Equivalent to calling PostTaskAndReply with default TaskTraits. |
| 110 | static bool PostTaskAndReply(const Location& from_here, |
| 111 | OnceClosure task, |
| 112 | OnceClosure reply); |
| 113 | |
| 114 | // Equivalent to calling PostTaskAndReplyWithResult with default TaskTraits. |
| 115 | // |
| 116 | // Though RepeatingCallback is convertible to OnceCallback, we need a |
| 117 | // CallbackType template since we can not use template deduction and object |
| 118 | // conversion at once on the overload resolution. |
| 119 | // TODO(crbug.com/714018): Update all callers of the RepeatingCallback version |
| 120 | // to use OnceCallback and remove the CallbackType template. |
| 121 | template <template <typename> class CallbackType, |
| 122 | typename TaskReturnType, |
| 123 | typename ReplyArgType, |
| 124 | typename = EnableIfIsBaseCallback<CallbackType>> |
| 125 | static bool PostTaskAndReplyWithResult( |
| 126 | const Location& from_here, |
| 127 | CallbackType<TaskReturnType()> task, |
| 128 | CallbackType<void(ReplyArgType)> reply) { |
| 129 | return ThreadPool::PostTaskAndReplyWithResult(from_here, std::move(task), |
| 130 | std::move(reply)); |
| 131 | } |
| 132 | |
| 133 | // Posts |task| with specific |traits|. Returns false if the task definitely |
| 134 | // won't run because of current shutdown state. |
| 135 | static bool PostTask(const Location& from_here, |
| 136 | const TaskTraits& traits, |
| 137 | OnceClosure task); |
| 138 | |
| 139 | // Posts |task| with specific |traits|. |task| will not run before |delay| |
| 140 | // expires. Returns false if the task definitely won't run because of current |
| 141 | // shutdown state. |
| 142 | // |
| 143 | // Specify a BEST_EFFORT priority via |traits| if the task doesn't have to run |
| 144 | // as soon as |delay| expires. |
| 145 | static bool PostDelayedTask(const Location& from_here, |
| 146 | const TaskTraits& traits, |
| 147 | OnceClosure task, |
| 148 | TimeDelta delay); |
| 149 | |
| 150 | // Posts |task| with specific |traits| and posts |reply| on the caller's |
| 151 | // execution context (i.e. same sequence or thread and same TaskTraits if |
| 152 | // applicable) when |task| completes. Returns false if the task definitely |
| 153 | // won't run because of current shutdown state. Can only be called when |
| 154 | // SequencedTaskRunnerHandle::IsSet(). |
| 155 | static bool PostTaskAndReply(const Location& from_here, |
| 156 | const TaskTraits& traits, |
| 157 | OnceClosure task, |
| 158 | OnceClosure reply); |
| 159 | |
| 160 | // Posts |task| with specific |traits| and posts |reply| with the return value |
| 161 | // of |task| as argument on the caller's execution context (i.e. same sequence |
| 162 | // or thread and same TaskTraits if applicable) when |task| completes. Returns |
| 163 | // false if the task definitely won't run because of current shutdown state. |
| 164 | // Can only be called when SequencedTaskRunnerHandle::IsSet(). |
| 165 | // |
| 166 | // Though RepeatingCallback is convertible to OnceCallback, we need a |
| 167 | // CallbackType template since we can not use template deduction and object |
| 168 | // conversion at once on the overload resolution. |
| 169 | // TODO(crbug.com/714018): Update all callers of the RepeatingCallback version |
| 170 | // to use OnceCallback and remove the CallbackType template. |
| 171 | template <template <typename> class CallbackType, |
| 172 | typename TaskReturnType, |
| 173 | typename ReplyArgType, |
| 174 | typename = EnableIfIsBaseCallback<CallbackType>> |
| 175 | bool PostTaskAndReplyWithResult(const Location& from_here, |
| 176 | const TaskTraits& traits, |
| 177 | CallbackType<TaskReturnType()> task, |
| 178 | CallbackType<void(ReplyArgType)> reply) { |
| 179 | auto* result = new std::unique_ptr<TaskReturnType>(); |
| 180 | return PostTaskAndReply( |
| 181 | from_here, traits, |
| 182 | BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, |
| 183 | std::move(task), result), |
| 184 | BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>, |
| 185 | std::move(reply), Owned(result))); |
| 186 | } |
| 187 | |
| 188 | // Returns a TaskRunner whose PostTask invocations result in scheduling tasks |
| 189 | // using |traits|. Tasks may run in any order and in parallel. |
| 190 | static scoped_refptr<TaskRunner> CreateTaskRunner(const TaskTraits& traits); |
| 191 | |
| 192 | // Returns a SequencedTaskRunner whose PostTask invocations result in |
| 193 | // scheduling tasks using |traits|. Tasks run one at a time in posting order. |
| 194 | static scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunner( |
| 195 | const TaskTraits& traits); |
| 196 | |
| 197 | // Returns a task runner whose PostTask invocations result in scheduling tasks |
| 198 | // using |traits|. The priority in |traits| can be updated at any time via |
| 199 | // UpdateableSequencedTaskRunner::UpdatePriority(). An update affects all |
| 200 | // tasks posted to the task runner that aren't running yet. Tasks run one at a |
| 201 | // time in posting order. |
| 202 | // |
| 203 | // |traits| requirements: |
| 204 | // - base::ThreadPolicy must be specified if the priority of the task runner |
| 205 | // will ever be increased from BEST_EFFORT. |
| 206 | static scoped_refptr<UpdateableSequencedTaskRunner> |
| 207 | CreateUpdateableSequencedTaskRunner(const TaskTraits& traits); |
| 208 | |
| 209 | // Returns a SingleThreadTaskRunner whose PostTask invocations result in |
| 210 | // scheduling tasks using |traits| on a thread determined by |thread_mode|. |
| 211 | // See base/task/single_thread_task_runner_thread_mode.h for |thread_mode| |
| 212 | // details. If |traits| identifies an existing thread, |
| 213 | // SingleThreadTaskRunnerThreadMode::SHARED must be used. Tasks run on a |
| 214 | // single thread in posting order. |
| 215 | // |
| 216 | // If all you need is to make sure that tasks don't run concurrently (e.g. |
| 217 | // because they access a data structure which is not thread-safe), use |
| 218 | // CreateSequencedTaskRunner(). Only use this if you rely on a thread-affine |
| 219 | // API (it might be safer to assume thread-affinity when dealing with |
| 220 | // under-documented third-party APIs, e.g. other OS') or share data across |
| 221 | // tasks using thread-local storage. |
| 222 | static scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunner( |
| 223 | const TaskTraits& traits, |
| 224 | SingleThreadTaskRunnerThreadMode thread_mode = |
| 225 | SingleThreadTaskRunnerThreadMode::SHARED); |
| 226 | |
| 227 | #if defined(OS_WIN) |
| 228 | // Returns a SingleThreadTaskRunner whose PostTask invocations result in |
| 229 | // scheduling tasks using |traits| in a COM Single-Threaded Apartment on a |
| 230 | // thread determined by |thread_mode|. See |
| 231 | // base/task/single_thread_task_runner_thread_mode.h for |thread_mode| |
| 232 | // details. If |traits| identifies an existing thread, |
| 233 | // SingleThreadTaskRunnerThreadMode::SHARED must be used. Tasks run in the |
| 234 | // same Single-Threaded Apartment in posting order for the returned |
| 235 | // SingleThreadTaskRunner. There is not necessarily a one-to-one |
| 236 | // correspondence between SingleThreadTaskRunners and Single-Threaded |
| 237 | // Apartments. The implementation is free to share apartments or create new |
| 238 | // apartments as necessary. In either case, care should be taken to make sure |
| 239 | // COM pointers are not smuggled across apartments. |
| 240 | static scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunner( |
| 241 | const TaskTraits& traits, |
| 242 | SingleThreadTaskRunnerThreadMode thread_mode = |
| 243 | SingleThreadTaskRunnerThreadMode::SHARED); |
| 244 | #endif // defined(OS_WIN) |
| 245 | }; |
| 246 | |
| 247 | } // namespace base |
| 248 | |
| 249 | #endif // BASE_TASK_THREAD_POOL_H_ |