fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 1 | # Threading and Tasks in Chrome |
| 2 | |
| 3 | [TOC] |
| 4 | |
Gabriel Charette | 8917f4c | 2018-11-22 15:50:28 | [diff] [blame] | 5 | Note: See [Threading and Tasks FAQ](threading_and_tasks_faq.md) for more |
| 6 | examples. |
| 7 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 8 | ## Overview |
| 9 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 10 | Chromium is a very multithreaded product. We try to keep the UI as responsive as |
| 11 | possible, and this means not blocking the UI thread with any blocking I/O or |
| 12 | other expensive operations. Our approach is to use message passing as the way of |
| 13 | communicating between threads. We discourage locking and threadsafe |
| 14 | objects. Instead, objects live on only one thread, we pass messages between |
| 15 | threads for communication, and we use callback interfaces (implemented by |
| 16 | message passing) for most cross-thread requests. |
| 17 | |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 18 | ### Nomenclature |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 19 | * **Thread-unsafe**: The vast majority of types in Chromium are thread-unsafe |
| 20 | by design. Access to such types/methods must be synchronized, typically by |
| 21 | sequencing access through a single `base::SequencedTaskRunner` (this should |
| 22 | be enforced by a `SEQUENCE_CHECKER`) or via low-level synchronization (e.g. |
| 23 | locks -- but [prefer sequences](#Using-Sequences-Instead-of-Locks)). |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 24 | * **Thread-affine**: Such types/methods need to be always accessed from the |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 25 | same physical thread (i.e. from the same `base::SingleThreadTaskRunner`) and |
| 26 | should use `THREAD_CHECKER` to verify that they are. Short of using a |
| 27 | third-party API or having a leaf dependency which is thread-affine: there's |
| 28 | pretty much no reason for a type to be thread-affine in Chromium. Note that |
| 29 | `base::SingleThreadTaskRunner` is-a `base::SequencedTaskRunner` so |
| 30 | thread-affine is a subset of thread-unsafe. Thread-affine is also sometimes |
| 31 | referred to as **thread-hostile**. |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 32 | * **Thread-safe**: Such types/methods can be safely accessed concurrently. |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 33 | * **Thread-compatible**: Such types provide safe concurrent access to const |
| 34 | methods but require synchronization for non-const (or mixed const/non-const |
| 35 | access). Chromium doesn't expose reader-writer locks; as such, the only use |
| 36 | case for this is objects (typically globals) which are initialized once in a |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 37 | thread-safe manner (either in the single-threaded phase of startup or lazily |
| 38 | through a thread-safe static-local-initialization paradigm a la |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 39 | `base::NoDestructor`) and forever after immutable. |
| 40 | * **Immutable**: A subset of thread-compatible types which cannot be modified |
| 41 | after construction. |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 42 | * **Sequence-friendly**: Such types/methods are thread-unsafe types which |
| 43 | support being invoked from a `base::SequencedTaskRunner`. Ideally this would |
| 44 | be the case for all thread-unsafe types but legacy code sometimes has |
| 45 | overzealous checks that enforce thread-affinity in mere thread-unsafe |
| 46 | scenarios. See [Prefer Sequences to Threads](#prefer-sequences-to-threads) |
| 47 | below for more details. |
| 48 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 49 | ### Threads |
| 50 | |
| 51 | Every Chrome process has |
| 52 | |
| 53 | * a main thread |
| 54 | * in the browser process: updates the UI |
| 55 | * in renderer processes: runs most of Blink |
| 56 | * an IO thread |
| 57 | * in the browser process: handles IPCs and network requests |
| 58 | * in renderer processes: handles IPCs |
| 59 | * a few more special-purpose threads |
| 60 | * and a pool of general-purpose threads |
| 61 | |
| 62 | Most threads have a loop that gets tasks from a queue and runs them (the queue |
| 63 | may be shared between multiple threads). |
| 64 | |
| 65 | ### Tasks |
| 66 | |
| 67 | A task is a `base::OnceClosure` added to a queue for asynchronous execution. |
| 68 | |
| 69 | A `base::OnceClosure` stores a function pointer and arguments. It has a `Run()` |
| 70 | method that invokes the function pointer using the bound arguments. It is |
| 71 | created using `base::BindOnce`. (ref. [Callback<> and Bind() |
| 72 | documentation](callback.md)). |
| 73 | |
| 74 | ``` |
| 75 | void TaskA() {} |
| 76 | void TaskB(int v) {} |
| 77 | |
| 78 | auto task_a = base::BindOnce(&TaskA); |
| 79 | auto task_b = base::BindOnce(&TaskB, 42); |
| 80 | ``` |
| 81 | |
| 82 | A group of tasks can be executed in one of the following ways: |
| 83 | |
| 84 | * [Parallel](#Posting-a-Parallel-Task): No task execution ordering, possibly all |
| 85 | at once on any thread |
| 86 | * [Sequenced](#Posting-a-Sequenced-Task): Tasks executed in posting order, one |
| 87 | at a time on any thread. |
| 88 | * [Single Threaded](#Posting-Multiple-Tasks-to-the-Same-Thread): Tasks executed |
| 89 | in posting order, one at a time on a single thread. |
| 90 | * [COM Single Threaded](#Posting-Tasks-to-a-COM-Single-Thread-Apartment-STA_Thread-Windows_): |
| 91 | A variant of single threaded with COM initialized. |
| 92 | |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 93 | ### Prefer Sequences to Threads |
| 94 | |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 95 | **Sequenced execution mode is far preferred to Single Threaded** in scenarios |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 96 | that require mere thread-safety as it opens up scheduling paradigms that |
| 97 | wouldn't be possible otherwise (sequences can hop threads instead of being stuck |
| 98 | behind unrelated work on a dedicated thread). Ability to hop threads also means |
| 99 | the thread count can dynamically adapt to the machine's true resource |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 100 | availability (increased parallelism on bigger machines, avoids trashing |
| 101 | resources on smaller machines). |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 102 | |
| 103 | Many core APIs were recently made sequence-friendly (classes are rarely |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 104 | thread-affine -- i.e. only when using third-party APIs that are thread-affine; |
| 105 | even ThreadLocalStorage has a SequenceLocalStorage equivalent). But the codebase |
| 106 | has long evolved assuming single-threaded contexts... If your class could run on |
| 107 | a sequence but is blocked by an overzealous use of |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 108 | ThreadChecker/ThreadTaskRunnerHandle/SingleThreadTaskRunner in a leaf |
| 109 | dependency, consider fixing that dependency for everyone's benefit (or at the |
| 110 | very least file a blocking bug against https://crbug.com/675631 and flag your |
| 111 | use of base::CreateSingleThreadTaskRunnerWithTraits() with a TODO against your |
| 112 | bug to use base::CreateSequencedTaskRunnerWithTraits() when fixed). |
| 113 | |
Gabriel Charette | 01567ac | 2017-06-09 15:31:10 | [diff] [blame] | 114 | Detailed documentation on how to migrate from single-threaded contexts to |
Gabriel Charette | 8917f4c | 2018-11-22 15:50:28 | [diff] [blame] | 115 | sequenced contexts can be found [here](threading_and_tasks_faq.md#How-to-migrate-from-SingleThreadTaskRunner-to-SequencedTaskRunner). |
Gabriel Charette | 01567ac | 2017-06-09 15:31:10 | [diff] [blame] | 116 | |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 117 | The discussion below covers all of these ways to execute tasks in details. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 118 | |
| 119 | ## Posting a Parallel Task |
| 120 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 121 | ### Direct Posting to the Thread Pool |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 122 | |
| 123 | A task that can run on any thread and doesn’t have ordering or mutual exclusion |
| 124 | requirements with other tasks should be posted using one of the |
| 125 | `base::PostTask*()` functions defined in |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 126 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 127 | |
| 128 | ```cpp |
| 129 | base::PostTask(FROM_HERE, base::BindOnce(&Task)); |
| 130 | ``` |
| 131 | |
| 132 | This posts tasks with default traits. |
| 133 | |
| 134 | The `base::PostTask*WithTraits()` functions allow the caller to provide |
| 135 | additional details about the task via TaskTraits (ref. |
| 136 | [Annotating Tasks with TaskTraits](#Annotating-Tasks-with-TaskTraits)). |
| 137 | |
| 138 | ```cpp |
| 139 | base::PostTaskWithTraits( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 140 | FROM_HERE, {base::TaskPriority::BEST_EFFORT, MayBlock()}, |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 141 | base::BindOnce(&Task)); |
| 142 | ``` |
| 143 | |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 144 | ### Posting via a TaskRunner |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 145 | |
| 146 | A parallel |
| 147 | [`TaskRunner`](https://cs.chromium.org/chromium/src/base/task_runner.h) is an |
| 148 | alternative to calling `base::PostTask*()` directly. This is mainly useful when |
| 149 | it isn’t known in advance whether tasks will be posted in parallel, in sequence, |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 150 | or to a single-thread (ref. |
| 151 | [Posting a Sequenced Task](#Posting-a-Sequenced-Task), |
| 152 | [Posting Multiple Tasks to the Same Thread](#Posting-Multiple-Tasks-to-the-Same-Thread)). |
| 153 | Since `TaskRunner` is the base class of `SequencedTaskRunner` and |
| 154 | `SingleThreadTaskRunner`, a `scoped_refptr<TaskRunner>` member can hold a |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 155 | `TaskRunner`, a `SequencedTaskRunner` or a `SingleThreadTaskRunner`. |
| 156 | |
| 157 | ```cpp |
| 158 | class A { |
| 159 | public: |
| 160 | A() = default; |
| 161 | |
| 162 | void set_task_runner_for_testing( |
| 163 | scoped_refptr<base::TaskRunner> task_runner) { |
| 164 | task_runner_ = std::move(task_runner); |
| 165 | } |
| 166 | |
| 167 | void DoSomething() { |
| 168 | // In production, A is always posted in parallel. In test, it is posted to |
| 169 | // the TaskRunner provided via set_task_runner_for_testing(). |
| 170 | task_runner_->PostTask(FROM_HERE, base::BindOnce(&A)); |
| 171 | } |
| 172 | |
| 173 | private: |
| 174 | scoped_refptr<base::TaskRunner> task_runner_ = |
| 175 | base::CreateTaskRunnerWithTraits({base::TaskPriority::USER_VISIBLE}); |
| 176 | }; |
| 177 | ``` |
| 178 | |
| 179 | Unless a test needs to control precisely how tasks are executed, it is preferred |
| 180 | to call `base::PostTask*()` directly (ref. [Testing](#Testing) for less invasive |
| 181 | ways of controlling tasks in tests). |
| 182 | |
| 183 | ## Posting a Sequenced Task |
| 184 | |
| 185 | A sequence is a set of tasks that run one at a time in posting order (not |
| 186 | necessarily on the same thread). To post tasks as part of a sequence, use a |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 187 | [`SequencedTaskRunner`](https://cs.chromium.org/chromium/src/base/sequenced_task_runner.h). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 188 | |
| 189 | ### Posting to a New Sequence |
| 190 | |
| 191 | A `SequencedTaskRunner` can be created by |
| 192 | `base::CreateSequencedTaskRunnerWithTraits()`. |
| 193 | |
| 194 | ```cpp |
| 195 | scoped_refptr<SequencedTaskRunner> sequenced_task_runner = |
| 196 | base::CreateSequencedTaskRunnerWithTraits(...); |
| 197 | |
| 198 | // TaskB runs after TaskA completes. |
| 199 | sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA)); |
| 200 | sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB)); |
| 201 | ``` |
| 202 | |
| 203 | ### Posting to the Current Sequence |
| 204 | |
| 205 | The `SequencedTaskRunner` to which the current task was posted can be obtained |
| 206 | via |
| 207 | [`SequencedTaskRunnerHandle::Get()`](https://cs.chromium.org/chromium/src/base/threading/sequenced_task_runner_handle.h). |
| 208 | |
| 209 | *** note |
| 210 | **NOTE:** it is invalid to call `SequencedTaskRunnerHandle::Get()` from a |
| 211 | parallel task, but it is valid from a single-threaded task (a |
| 212 | `SingleThreadTaskRunner` is a `SequencedTaskRunner`). |
| 213 | *** |
| 214 | |
| 215 | ```cpp |
| 216 | // The task will run after any task that has already been posted |
| 217 | // to the SequencedTaskRunner to which the current task was posted |
| 218 | // (in particular, it will run after the current task completes). |
| 219 | // It is also guaranteed that it won’t run concurrently with any |
| 220 | // task posted to that SequencedTaskRunner. |
| 221 | base::SequencedTaskRunnerHandle::Get()-> |
| 222 | PostTask(FROM_HERE, base::BindOnce(&Task)); |
| 223 | ``` |
| 224 | |
| 225 | ## Using Sequences Instead of Locks |
| 226 | |
| 227 | Usage of locks is discouraged in Chrome. Sequences inherently provide |
Gabriel Charette | a3ccc97 | 2018-11-13 14:43:12 | [diff] [blame] | 228 | thread-safety. Prefer classes that are always accessed from the same |
| 229 | sequence to managing your own thread-safety with locks. |
| 230 | |
| 231 | **Thread-safe but not thread-affine; how so?** Tasks posted to the same sequence |
| 232 | will run in sequential order. After a sequenced task completes, the next task |
| 233 | may be picked up by a different worker thread, but that task is guaranteed to |
| 234 | see any side-effects caused by the previous one(s) on its sequence. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 235 | |
| 236 | ```cpp |
| 237 | class A { |
| 238 | public: |
| 239 | A() { |
| 240 | // Do not require accesses to be on the creation sequence. |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 241 | DETACH_FROM_SEQUENCE(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 242 | } |
| 243 | |
| 244 | void AddValue(int v) { |
| 245 | // Check that all accesses are on the same sequence. |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 246 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 247 | values_.push_back(v); |
| 248 | } |
| 249 | |
| 250 | private: |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 251 | SEQUENCE_CHECKER(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 252 | |
| 253 | // No lock required, because all accesses are on the |
| 254 | // same sequence. |
| 255 | std::vector<int> values_; |
| 256 | }; |
| 257 | |
| 258 | A a; |
| 259 | scoped_refptr<SequencedTaskRunner> task_runner_for_a = ...; |
Mike Bjorge | d3a0984 | 2018-05-15 18:37:28 | [diff] [blame] | 260 | task_runner_for_a->PostTask(FROM_HERE, |
| 261 | base::BindOnce(&A::AddValue, base::Unretained(&a), 42)); |
| 262 | task_runner_for_a->PostTask(FROM_HERE, |
| 263 | base::BindOnce(&A::AddValue, base::Unretained(&a), 27)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 264 | |
| 265 | // Access from a different sequence causes a DCHECK failure. |
| 266 | scoped_refptr<SequencedTaskRunner> other_task_runner = ...; |
| 267 | other_task_runner->PostTask(FROM_HERE, |
Mike Bjorge | d3a0984 | 2018-05-15 18:37:28 | [diff] [blame] | 268 | base::BindOnce(&A::AddValue, base::Unretained(&a), 1)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 269 | ``` |
| 270 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 271 | Locks should only be used to swap in a shared data structure that can be |
| 272 | accessed on multiple threads. If one thread updates it based on expensive |
| 273 | computation or through disk access, then that slow work should be done without |
| 274 | holding on to the lock. Only when the result is available should the lock be |
| 275 | used to swap in the new data. An example of this is in PluginList::LoadPlugins |
Haiyang Pan | a232802 | 2019-04-03 12:07:26 | [diff] [blame] | 276 | ([`content/browser/plugin_list.cc`](https://cs.chromium.org/chromium/src/content/browser/plugin_list.cc)). If you must use locks, |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 277 | [here](https://www.chromium.org/developers/lock-and-condition-variable) are some |
| 278 | best practices and pitfalls to avoid. |
| 279 | |
| 280 | In order to write non-blocking code, many APIs in Chromium are asynchronous. |
| 281 | Usually this means that they either need to be executed on a particular |
| 282 | thread/sequence and will return results via a custom delegate interface, or they |
| 283 | take a `base::Callback<>` object that is called when the requested operation is |
| 284 | completed. Executing work on a specific thread/sequence is covered in the |
| 285 | PostTask sections above. |
| 286 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 287 | ## Posting Multiple Tasks to the Same Thread |
| 288 | |
| 289 | If multiple tasks need to run on the same thread, post them to a |
| 290 | [`SingleThreadTaskRunner`](https://cs.chromium.org/chromium/src/base/single_thread_task_runner.h). |
| 291 | All tasks posted to the same `SingleThreadTaskRunner` run on the same thread in |
| 292 | posting order. |
| 293 | |
| 294 | ### Posting to the Main Thread or to the IO Thread in the Browser Process |
| 295 | |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 296 | To post tasks to the main thread or to the IO thread, use |
| 297 | `base::PostTaskWithTraits()` or get the appropriate SingleThreadTaskRunner using |
| 298 | `base::CreateSingleThreadTaskRunnerWithTraits`, supplying a `BrowserThread::ID` |
| 299 | as trait. For this, you'll also need to include |
| 300 | [`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 301 | |
| 302 | ```cpp |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 303 | base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, ...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 304 | |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 305 | base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 306 | ->PostTask(FROM_HERE, ...); |
| 307 | ``` |
| 308 | |
| 309 | The main thread and the IO thread are already super busy. Therefore, prefer |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 310 | posting to a general purpose thread when possible (ref. |
| 311 | [Posting a Parallel Task](#Posting-a-Parallel-Task), |
| 312 | [Posting a Sequenced task](#Posting-a-Sequenced-Task)). |
| 313 | Good reasons to post to the main thread are to update the UI or access objects |
| 314 | that are bound to it (e.g. `Profile`). A good reason to post to the IO thread is |
| 315 | to access the internals of components that are bound to it (e.g. IPCs, network). |
| 316 | Note: It is not necessary to have an explicit post task to the IO thread to |
| 317 | send/receive an IPC or send/receive data on the network. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 318 | |
| 319 | ### Posting to the Main Thread in a Renderer Process |
| 320 | TODO |
| 321 | |
| 322 | ### Posting to a Custom SingleThreadTaskRunner |
| 323 | |
| 324 | If multiple tasks need to run on the same thread and that thread doesn’t have to |
| 325 | be the main thread or the IO thread, post them to a `SingleThreadTaskRunner` |
| 326 | created by `base::CreateSingleThreadTaskRunnerWithTraits`. |
| 327 | |
| 328 | ```cpp |
| 329 | scoped_refptr<SequencedTaskRunner> single_thread_task_runner = |
| 330 | base::CreateSingleThreadTaskRunnerWithTraits(...); |
| 331 | |
| 332 | // TaskB runs after TaskA completes. Both tasks run on the same thread. |
| 333 | single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA)); |
| 334 | single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB)); |
| 335 | ``` |
| 336 | |
| 337 | *** note |
| 338 | **IMPORTANT:** You should rarely need this, most classes in Chromium require |
| 339 | thread-safety (which sequences provide) not thread-affinity. If an API you’re |
| 340 | using is incorrectly thread-affine (i.e. using |
| 341 | [`base::ThreadChecker`](https://cs.chromium.org/chromium/src/base/threading/thread_checker.h) |
| 342 | when it’s merely thread-unsafe and should use |
| 343 | [`base::SequenceChecker`](https://cs.chromium.org/chromium/src/base/sequence_checker.h)), |
Gabriel Charette | 41f4a48 | 2019-01-15 00:15:50 | [diff] [blame] | 344 | please consider |
| 345 | [`fixing it`](threading_and_tasks_faq.md#How-to-migrate-from-SingleThreadTaskRunner-to-SequencedTaskRunner) |
| 346 | instead of making things worse by also making your API thread-affine. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 347 | *** |
| 348 | |
| 349 | ### Posting to the Current Thread |
| 350 | |
| 351 | *** note |
| 352 | **IMPORTANT:** To post a task that needs mutual exclusion with the current |
| 353 | sequence of tasks but doesn’t absolutely need to run on the current thread, use |
| 354 | `SequencedTaskRunnerHandle::Get()` instead of `ThreadTaskRunnerHandle::Get()` |
| 355 | (ref. [Posting to the Current Sequence](#Posting-to-the-Current-Sequence)). That |
| 356 | will better document the requirements of the posted task. In a single-thread |
| 357 | task, `SequencedTaskRunnerHandle::Get()` is equivalent to |
| 358 | `ThreadTaskRunnerHandle::Get()`. |
| 359 | *** |
| 360 | |
| 361 | To post a task to the current thread, use [`ThreadTaskRunnerHandle`](https://cs.chromium.org/chromium/src/base/threading/thread_task_runner_handle.h). |
| 362 | |
| 363 | ```cpp |
| 364 | // The task will run on the current thread in the future. |
| 365 | base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 366 | FROM_HERE, base::BindOnce(&Task)); |
| 367 | ``` |
| 368 | |
| 369 | *** note |
| 370 | **NOTE:** It is invalid to call `ThreadTaskRunnerHandle::Get()` from a parallel |
| 371 | or a sequenced task. |
| 372 | *** |
| 373 | |
| 374 | ## Posting Tasks to a COM Single-Thread Apartment (STA) Thread (Windows) |
| 375 | |
| 376 | Tasks that need to run on a COM Single-Thread Apartment (STA) thread must be |
| 377 | posted to a `SingleThreadTaskRunner` returned by |
| 378 | `CreateCOMSTATaskRunnerWithTraits()`. As mentioned in [Posting Multiple Tasks to |
| 379 | the Same Thread](#Posting-Multiple-Tasks-to-the-Same-Thread), all tasks posted |
| 380 | to the same `SingleThreadTaskRunner` run on the same thread in posting order. |
| 381 | |
| 382 | ```cpp |
| 383 | // Task(A|B|C)UsingCOMSTA will run on the same COM STA thread. |
| 384 | |
| 385 | void TaskAUsingCOMSTA() { |
| 386 | // [ This runs on a COM STA thread. ] |
| 387 | |
| 388 | // Make COM STA calls. |
| 389 | // ... |
| 390 | |
| 391 | // Post another task to the current COM STA thread. |
| 392 | base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 393 | FROM_HERE, base::BindOnce(&TaskCUsingCOMSTA)); |
| 394 | } |
| 395 | void TaskBUsingCOMSTA() { } |
| 396 | void TaskCUsingCOMSTA() { } |
| 397 | |
| 398 | auto com_sta_task_runner = base::CreateCOMSTATaskRunnerWithTraits(...); |
| 399 | com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskAUsingCOMSTA)); |
| 400 | com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskBUsingCOMSTA)); |
| 401 | ``` |
| 402 | |
| 403 | ## Annotating Tasks with TaskTraits |
| 404 | |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 405 | [`TaskTraits`](https://cs.chromium.org/chromium/src/base/task/task_traits.h) |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 406 | encapsulate information about a task that helps the thread pool make better |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 407 | scheduling decisions. |
| 408 | |
| 409 | All `PostTask*()` functions in |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 410 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h) |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 411 | have an overload that takes `TaskTraits` as argument and one that doesn’t. The |
| 412 | overload that doesn’t take `TaskTraits` as argument is appropriate for tasks |
| 413 | that: |
| 414 | - Don’t block (ref. MayBlock and WithBaseSyncPrimitives). |
| 415 | - Prefer inheriting the current priority to specifying their own. |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 416 | - Can either block shutdown or be skipped on shutdown (thread pool is free to |
| 417 | choose a fitting default). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 418 | Tasks that don’t match this description must be posted with explicit TaskTraits. |
| 419 | |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 420 | [`base/task/task_traits.h`](https://cs.chromium.org/chromium/src/base/task/task_traits.h) |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 421 | provides exhaustive documentation of available traits. The content layer also |
| 422 | provides additional traits in |
| 423 | [`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h) |
| 424 | to facilitate posting a task onto a BrowserThread. |
| 425 | |
| 426 | Below are some examples of how to specify `TaskTraits`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 427 | |
| 428 | ```cpp |
| 429 | // This task has no explicit TaskTraits. It cannot block. Its priority |
| 430 | // is inherited from the calling context (e.g. if it is posted from |
Gabriel Charette | 141a44258 | 2018-07-27 21:23:25 | [diff] [blame] | 431 | // a BEST_EFFORT task, it will have a BEST_EFFORT priority). It will either |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 432 | // block shutdown or be skipped on shutdown. |
| 433 | base::PostTask(FROM_HERE, base::BindOnce(...)); |
| 434 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 435 | // This task has the highest priority. The thread pool will try to |
Gabriel Charette | 141a44258 | 2018-07-27 21:23:25 | [diff] [blame] | 436 | // run it before USER_VISIBLE and BEST_EFFORT tasks. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 437 | base::PostTaskWithTraits( |
| 438 | FROM_HERE, {base::TaskPriority::USER_BLOCKING}, |
| 439 | base::BindOnce(...)); |
| 440 | |
| 441 | // This task has the lowest priority and is allowed to block (e.g. it |
| 442 | // can read a file from disk). |
| 443 | base::PostTaskWithTraits( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 444 | FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 445 | base::BindOnce(...)); |
| 446 | |
| 447 | // This task blocks shutdown. The process won't exit before its |
| 448 | // execution is complete. |
| 449 | base::PostTaskWithTraits( |
| 450 | FROM_HERE, {base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, |
| 451 | base::BindOnce(...)); |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 452 | |
| 453 | // This task will run on the Browser UI thread. |
| 454 | base::PostTaskWithTraits( |
| 455 | FROM_HERE, {content::BrowserThread::UI}, |
| 456 | base::BindOnce(...)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 457 | ``` |
| 458 | |
| 459 | ## Keeping the Browser Responsive |
| 460 | |
| 461 | Do not perform expensive work on the main thread, the IO thread or any sequence |
| 462 | that is expected to run tasks with a low latency. Instead, perform expensive |
| 463 | work asynchronously using `base::PostTaskAndReply*()` or |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 464 | `SequencedTaskRunner::PostTaskAndReply()`. Note that asynchronous/overlapped |
| 465 | I/O on the IO thread are fine. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 466 | |
| 467 | Example: Running the code below on the main thread will prevent the browser from |
| 468 | responding to user input for a long time. |
| 469 | |
| 470 | ```cpp |
| 471 | // GetHistoryItemsFromDisk() may block for a long time. |
| 472 | // AddHistoryItemsToOmniboxDropDown() updates the UI and therefore must |
| 473 | // be called on the main thread. |
| 474 | AddHistoryItemsToOmniboxDropdown(GetHistoryItemsFromDisk("keyword")); |
| 475 | ``` |
| 476 | |
| 477 | The code below solves the problem by scheduling a call to |
| 478 | `GetHistoryItemsFromDisk()` in a thread pool followed by a call to |
| 479 | `AddHistoryItemsToOmniboxDropdown()` on the origin sequence (the main thread in |
| 480 | this case). The return value of the first call is automatically provided as |
| 481 | argument to the second call. |
| 482 | |
| 483 | ```cpp |
| 484 | base::PostTaskWithTraitsAndReplyWithResult( |
| 485 | FROM_HERE, {base::MayBlock()}, |
| 486 | base::BindOnce(&GetHistoryItemsFromDisk, "keyword"), |
| 487 | base::BindOnce(&AddHistoryItemsToOmniboxDropdown)); |
| 488 | ``` |
| 489 | |
| 490 | ## Posting a Task with a Delay |
| 491 | |
| 492 | ### Posting a One-Off Task with a Delay |
| 493 | |
| 494 | To post a task that must run once after a delay expires, use |
| 495 | `base::PostDelayedTask*()` or `TaskRunner::PostDelayedTask()`. |
| 496 | |
| 497 | ```cpp |
| 498 | base::PostDelayedTaskWithTraits( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 499 | FROM_HERE, {base::TaskPriority::BEST_EFFORT}, base::BindOnce(&Task), |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 500 | base::TimeDelta::FromHours(1)); |
| 501 | |
| 502 | scoped_refptr<base::SequencedTaskRunner> task_runner = |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 503 | base::CreateSequencedTaskRunnerWithTraits({base::TaskPriority::BEST_EFFORT}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 504 | task_runner->PostDelayedTask( |
| 505 | FROM_HERE, base::BindOnce(&Task), base::TimeDelta::FromHours(1)); |
| 506 | ``` |
| 507 | |
| 508 | *** note |
| 509 | **NOTE:** A task that has a 1-hour delay probably doesn’t have to run right away |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 510 | when its delay expires. Specify `base::TaskPriority::BEST_EFFORT` to prevent it |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 511 | from slowing down the browser when its delay expires. |
| 512 | *** |
| 513 | |
| 514 | ### Posting a Repeating Task with a Delay |
| 515 | To post a task that must run at regular intervals, |
| 516 | use [`base::RepeatingTimer`](https://cs.chromium.org/chromium/src/base/timer/timer.h). |
| 517 | |
| 518 | ```cpp |
| 519 | class A { |
| 520 | public: |
| 521 | ~A() { |
| 522 | // The timer is stopped automatically when it is deleted. |
| 523 | } |
| 524 | void StartDoingStuff() { |
| 525 | timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1), |
| 526 | this, &MyClass::DoStuff); |
| 527 | } |
| 528 | void StopDoingStuff() { |
| 529 | timer_.Stop(); |
| 530 | } |
| 531 | private: |
| 532 | void DoStuff() { |
| 533 | // This method is called every second on the sequence that invoked |
| 534 | // StartDoingStuff(). |
| 535 | } |
| 536 | base::RepeatingTimer timer_; |
| 537 | }; |
| 538 | ``` |
| 539 | |
| 540 | ## Cancelling a Task |
| 541 | |
| 542 | ### Using base::WeakPtr |
| 543 | |
| 544 | [`base::WeakPtr`](https://cs.chromium.org/chromium/src/base/memory/weak_ptr.h) |
| 545 | can be used to ensure that any callback bound to an object is canceled when that |
| 546 | object is destroyed. |
| 547 | |
| 548 | ```cpp |
| 549 | int Compute() { … } |
| 550 | |
| 551 | class A { |
| 552 | public: |
| 553 | A() : weak_ptr_factory_(this) {} |
| 554 | |
| 555 | void ComputeAndStore() { |
| 556 | // Schedule a call to Compute() in a thread pool followed by |
| 557 | // a call to A::Store() on the current sequence. The call to |
| 558 | // A::Store() is canceled when |weak_ptr_factory_| is destroyed. |
| 559 | // (guarantees that |this| will not be used-after-free). |
| 560 | base::PostTaskAndReplyWithResult( |
| 561 | FROM_HERE, base::BindOnce(&Compute), |
| 562 | base::BindOnce(&A::Store, weak_ptr_factory_.GetWeakPtr())); |
| 563 | } |
| 564 | |
| 565 | private: |
| 566 | void Store(int value) { value_ = value; } |
| 567 | |
| 568 | int value_; |
| 569 | base::WeakPtrFactory<A> weak_ptr_factory_; |
| 570 | }; |
| 571 | ``` |
| 572 | |
| 573 | Note: `WeakPtr` is not thread-safe: `GetWeakPtr()`, `~WeakPtrFactory()`, and |
| 574 | `Compute()` (bound to a `WeakPtr`) must all run on the same sequence. |
| 575 | |
| 576 | ### Using base::CancelableTaskTracker |
| 577 | |
| 578 | [`base::CancelableTaskTracker`](https://cs.chromium.org/chromium/src/base/task/cancelable_task_tracker.h) |
| 579 | allows cancellation to happen on a different sequence than the one on which |
| 580 | tasks run. Keep in mind that `CancelableTaskTracker` cannot cancel tasks that |
| 581 | have already started to run. |
| 582 | |
| 583 | ```cpp |
| 584 | auto task_runner = base::CreateTaskRunnerWithTraits(base::TaskTraits()); |
| 585 | base::CancelableTaskTracker cancelable_task_tracker; |
| 586 | cancelable_task_tracker.PostTask(task_runner.get(), FROM_HERE, |
Peter Kasting | 341e1fb | 2018-02-24 00:03:01 | [diff] [blame] | 587 | base::DoNothing()); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 588 | // Cancels Task(), only if it hasn't already started running. |
| 589 | cancelable_task_tracker.TryCancelAll(); |
| 590 | ``` |
| 591 | |
| 592 | ## Testing |
| 593 | |
| 594 | To test code that uses `base::ThreadTaskRunnerHandle`, |
| 595 | `base::SequencedTaskRunnerHandle` or a function in |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 596 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h), instantiate a |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 597 | [`base::test::ScopedTaskEnvironment`](https://cs.chromium.org/chromium/src/base/test/scoped_task_environment.h) |
| 598 | for the scope of the test. |
| 599 | |
Wez | d9e4cb77 | 2019-01-09 03:07:03 | [diff] [blame] | 600 | Tests can run the ScopedTaskEnvironment's message pump using a RunLoop, which |
| 601 | can be made to run until Quit, or to execute ready-to-run tasks and immediately |
| 602 | return. |
| 603 | |
| 604 | ScopedTaskEnvironment configures RunLoop::Run() to LOG(FATAL) if it hasn't been |
| 605 | explicitly quit after TestTimeouts::action_timeout(). This is preferable to |
| 606 | having the test hang if the code under test fails to trigger the RunLoop to |
| 607 | quit. The timeout can be overridden with ScopedRunTimeoutForTest. |
| 608 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 609 | ```cpp |
| 610 | class MyTest : public testing::Test { |
| 611 | public: |
| 612 | // ... |
| 613 | protected: |
| 614 | base::test::ScopedTaskEnvironment scoped_task_environment_; |
| 615 | }; |
| 616 | |
| 617 | TEST(MyTest, MyTest) { |
| 618 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&A)); |
| 619 | base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, |
| 620 | base::BindOnce(&B)); |
| 621 | base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( |
| 622 | FROM_HERE, base::BindOnce(&C), base::TimeDelta::Max()); |
| 623 | |
| 624 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until it is empty. |
| 625 | // Delayed tasks are not added to the queue until they are ripe for execution. |
| 626 | base::RunLoop().RunUntilIdle(); |
| 627 | // A and B have been executed. C is not ripe for execution yet. |
| 628 | |
| 629 | base::RunLoop run_loop; |
| 630 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&D)); |
| 631 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); |
| 632 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&E)); |
| 633 | |
| 634 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until QuitClosure is |
| 635 | // invoked. |
| 636 | run_loop.Run(); |
| 637 | // D and run_loop.QuitClosure() have been executed. E is still in the queue. |
| 638 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 639 | // Tasks posted to thread pool run asynchronously as they are posted. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 640 | base::PostTaskWithTraits(FROM_HERE, base::TaskTraits(), base::BindOnce(&F)); |
| 641 | auto task_runner = |
| 642 | base::CreateSequencedTaskRunnerWithTraits(base::TaskTraits()); |
| 643 | task_runner->PostTask(FROM_HERE, base::BindOnce(&G)); |
| 644 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 645 | // To block until all tasks posted to thread pool are done running: |
| 646 | base::ThreadPool::GetInstance()->FlushForTesting(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 647 | // F and G have been executed. |
| 648 | |
| 649 | base::PostTaskWithTraitsAndReplyWithResult( |
| 650 | FROM_HERE, base::TaskTrait(), |
| 651 | base::BindOnce(&H), base::BindOnce(&I)); |
| 652 | |
| 653 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until both the |
| 654 | // (Thread|Sequenced)TaskRunnerHandle queue and the TaskSchedule queue are |
| 655 | // empty: |
| 656 | scoped_task_environment_.RunUntilIdle(); |
| 657 | // E, H, I have been executed. |
| 658 | } |
| 659 | ``` |
| 660 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 661 | ## Using ThreadPool in a New Process |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 662 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 663 | ThreadPool needs to be initialized in a process before the functions in |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 664 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h) |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 665 | can be used. Initialization of ThreadPool in the Chrome browser process and |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 666 | child processes (renderer, GPU, utility) has already been taken care of. To use |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 667 | ThreadPool in another process, initialize ThreadPool early in the main |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 668 | function: |
| 669 | |
| 670 | ```cpp |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 671 | // This initializes and starts ThreadPool with default params. |
| 672 | base::ThreadPool::CreateAndStartWithDefaultParams(“process_name”); |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 673 | // The base/task/post_task.h API can now be used. Tasks will be // scheduled as |
| 674 | // they are posted. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 675 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 676 | // This initializes ThreadPool. |
| 677 | base::ThreadPool::Create(“process_name”); |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 678 | // The base/task/post_task.h API can now be used. No threads // will be created |
| 679 | // and no tasks will be scheduled until after Start() is called. |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 680 | base::ThreadPool::GetInstance()->Start(params); |
| 681 | // ThreadPool can now create threads and schedule tasks. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 682 | ``` |
| 683 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 684 | And shutdown ThreadPool late in the main function: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 685 | |
| 686 | ```cpp |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame^] | 687 | base::ThreadPool::GetInstance()->Shutdown(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 688 | // Tasks posted with TaskShutdownBehavior::BLOCK_SHUTDOWN and |
| 689 | // tasks posted with TaskShutdownBehavior::SKIP_ON_SHUTDOWN that |
| 690 | // have started to run before the Shutdown() call have now completed their |
| 691 | // execution. Tasks posted with |
| 692 | // TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN may still be |
| 693 | // running. |
| 694 | ``` |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 695 | ## TaskRunner ownership (encourage no dependency injection) |
Sebastien Marchand | c95489b | 2017-05-25 16:39:34 | [diff] [blame] | 696 | |
| 697 | TaskRunners shouldn't be passed through several components. Instead, the |
| 698 | components that uses a TaskRunner should be the one that creates it. |
| 699 | |
| 700 | See [this example](https://codereview.chromium.org/2885173002/) of a |
| 701 | refactoring where a TaskRunner was passed through a lot of components only to be |
| 702 | used in an eventual leaf. The leaf can and should now obtain its TaskRunner |
| 703 | directly from |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 704 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h). |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 705 | |
| 706 | Dependency injection of TaskRunners can still seldomly be useful to unit test a |
| 707 | component when triggering a specific race in a specific way is essential to the |
| 708 | test. For such cases the preferred approach is the following: |
| 709 | |
| 710 | ```cpp |
| 711 | class FooWithCustomizableTaskRunnerForTesting { |
| 712 | public: |
| 713 | |
| 714 | void SetBackgroundTaskRunnerForTesting( |
michaelpg | 12c0457 | 2017-06-26 23:25:06 | [diff] [blame] | 715 | scoped_refptr<base::SequencedTaskRunner> background_task_runner); |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 716 | |
| 717 | private: |
michaelpg | 12c0457 | 2017-06-26 23:25:06 | [diff] [blame] | 718 | scoped_refptr<base::SequencedTaskRunner> background_task_runner_ = |
| 719 | base::CreateSequencedTaskRunnerWithTraits( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 720 | {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 721 | } |
| 722 | ``` |
| 723 | |
| 724 | Note that this still allows removing all layers of plumbing between //chrome and |
| 725 | that component since unit tests will use the leaf layer directly. |
Gabriel Charette | 8917f4c | 2018-11-22 15:50:28 | [diff] [blame] | 726 | |
| 727 | ## FAQ |
| 728 | See [Threading and Tasks FAQ](threading_and_tasks_faq.md) for more examples. |