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