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 |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 173 | `base::ThreadPool::PostTask*()` functions defined in |
| 174 | [`base/task/thread_pool.h`](https://cs.chromium.org/chromium/src/base/task/thread_pool.h). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 175 | |
| 176 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 177 | base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(&Task)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 178 | ``` |
| 179 | |
| 180 | This posts tasks with default traits. |
| 181 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 182 | The `base::ThreadPool::PostTask*()` functions allow the caller to provide |
| 183 | additional details about the task via TaskTraits (ref. [Annotating Tasks with |
| 184 | TaskTraits](#Annotating-Tasks-with-TaskTraits)). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 185 | |
| 186 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 187 | base::ThreadPool::PostTask( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 188 | FROM_HERE, {base::TaskPriority::BEST_EFFORT, MayBlock()}, |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 189 | base::BindOnce(&Task)); |
| 190 | ``` |
| 191 | |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 192 | ### Posting via a TaskRunner |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 193 | |
| 194 | A parallel |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 195 | [`base::TaskRunner`](https://cs.chromium.org/chromium/src/base/task_runner.h) is |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 196 | an alternative to calling `base::ThreadPool::PostTask*()` directly. This is |
| 197 | mainly useful when it isn’t known in advance whether tasks will be posted in |
| 198 | parallel, in sequence, or to a single-thread (ref. [Posting a Sequenced |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 199 | Task](#Posting-a-Sequenced-Task), [Posting Multiple Tasks to the Same |
| 200 | Thread](#Posting-Multiple-Tasks-to-the-Same-Thread)). Since `base::TaskRunner` |
| 201 | is the base class of `base::SequencedTaskRunner` and |
| 202 | `base::SingleThreadTaskRunner`, a `scoped_refptr<TaskRunner>` member can hold a |
| 203 | `base::TaskRunner`, a `base::SequencedTaskRunner` or a |
| 204 | `base::SingleThreadTaskRunner`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 205 | |
| 206 | ```cpp |
| 207 | class A { |
| 208 | public: |
| 209 | A() = default; |
| 210 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 211 | void PostSomething() { |
| 212 | task_runner_->PostTask(FROM_HERE, base::BindOnce(&A, &DoSomething)); |
| 213 | } |
| 214 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 215 | void DoSomething() { |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 216 | } |
| 217 | |
| 218 | private: |
| 219 | scoped_refptr<base::TaskRunner> task_runner_ = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 220 | base::ThreadPool::CreateTaskRunner({base::TaskPriority::USER_VISIBLE}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 221 | }; |
| 222 | ``` |
| 223 | |
| 224 | Unless a test needs to control precisely how tasks are executed, it is preferred |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 225 | to call `base::ThreadPool::PostTask*()` directly (ref. [Testing](#Testing) for less invasive |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 226 | ways of controlling tasks in tests). |
| 227 | |
| 228 | ## Posting a Sequenced Task |
| 229 | |
| 230 | A sequence is a set of tasks that run one at a time in posting order (not |
| 231 | 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] | 232 | [`base::SequencedTaskRunner`](https://cs.chromium.org/chromium/src/base/sequenced_task_runner.h). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 233 | |
| 234 | ### Posting to a New Sequence |
| 235 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 236 | A `base::SequencedTaskRunner` can be created by |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 237 | `base::ThreadPool::CreateSequencedTaskRunner()`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 238 | |
| 239 | ```cpp |
| 240 | scoped_refptr<SequencedTaskRunner> sequenced_task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 241 | base::ThreadPool::CreateSequencedTaskRunner(...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 242 | |
| 243 | // TaskB runs after TaskA completes. |
| 244 | sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA)); |
| 245 | sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB)); |
| 246 | ``` |
| 247 | |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 248 | ### Posting to the Current (Virtual) Thread |
| 249 | |
Gabriel Charette | fee5566 | 2019-11-20 21:06:28 | [diff] [blame] | 250 | The preferred way of posting to the current (virtual) thread is via |
| 251 | `base::SequencedTaskRunnerHandle::Get()`. |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 252 | |
| 253 | ```cpp |
| 254 | // The task will run on the current (virtual) thread's default task queue. |
Gabriel Charette | fee5566 | 2019-11-20 21:06:28 | [diff] [blame] | 255 | base::SequencedTaskRunnerHandle::Get()->PostTask( |
| 256 | FROM_HERE, base::BindOnce(&Task); |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 257 | ``` |
| 258 | |
Gabriel Charette | fee5566 | 2019-11-20 21:06:28 | [diff] [blame] | 259 | Note that SequencedTaskRunnerHandle::Get() returns the default queue for the |
| 260 | current virtual thread. On threads with multiple task queues (e.g. |
| 261 | BrowserThread::UI) this can be a different queue than the one the current task |
| 262 | belongs to. The "current" task runner is intentionally not exposed via a static |
| 263 | getter. Either you know it already and can post to it directly or you don't and |
| 264 | the only sensible destination is the default queue. |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 265 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 266 | ## Using Sequences Instead of Locks |
| 267 | |
| 268 | Usage of locks is discouraged in Chrome. Sequences inherently provide |
Gabriel Charette | a3ccc97 | 2018-11-13 14:43:12 | [diff] [blame] | 269 | thread-safety. Prefer classes that are always accessed from the same |
| 270 | sequence to managing your own thread-safety with locks. |
| 271 | |
| 272 | **Thread-safe but not thread-affine; how so?** Tasks posted to the same sequence |
| 273 | will run in sequential order. After a sequenced task completes, the next task |
| 274 | may be picked up by a different worker thread, but that task is guaranteed to |
| 275 | see any side-effects caused by the previous one(s) on its sequence. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 276 | |
| 277 | ```cpp |
| 278 | class A { |
| 279 | public: |
| 280 | A() { |
| 281 | // Do not require accesses to be on the creation sequence. |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 282 | DETACH_FROM_SEQUENCE(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 283 | } |
| 284 | |
| 285 | void AddValue(int v) { |
| 286 | // Check that all accesses are on the same sequence. |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 287 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 288 | values_.push_back(v); |
| 289 | } |
| 290 | |
| 291 | private: |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 292 | SEQUENCE_CHECKER(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 293 | |
| 294 | // No lock required, because all accesses are on the |
| 295 | // same sequence. |
| 296 | std::vector<int> values_; |
| 297 | }; |
| 298 | |
| 299 | A a; |
| 300 | scoped_refptr<SequencedTaskRunner> task_runner_for_a = ...; |
Mike Bjorge | d3a0984 | 2018-05-15 18:37:28 | [diff] [blame] | 301 | task_runner_for_a->PostTask(FROM_HERE, |
| 302 | base::BindOnce(&A::AddValue, base::Unretained(&a), 42)); |
| 303 | task_runner_for_a->PostTask(FROM_HERE, |
| 304 | base::BindOnce(&A::AddValue, base::Unretained(&a), 27)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 305 | |
| 306 | // Access from a different sequence causes a DCHECK failure. |
| 307 | scoped_refptr<SequencedTaskRunner> other_task_runner = ...; |
| 308 | other_task_runner->PostTask(FROM_HERE, |
Mike Bjorge | d3a0984 | 2018-05-15 18:37:28 | [diff] [blame] | 309 | base::BindOnce(&A::AddValue, base::Unretained(&a), 1)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 310 | ``` |
| 311 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 312 | Locks should only be used to swap in a shared data structure that can be |
| 313 | accessed on multiple threads. If one thread updates it based on expensive |
| 314 | computation or through disk access, then that slow work should be done without |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 315 | holding the lock. Only when the result is available should the lock be used to |
| 316 | swap in the new data. An example of this is in PluginList::LoadPlugins |
| 317 | ([`content/browser/plugin_list.cc`](https://cs.chromium.org/chromium/src/content/browser/plugin_list.cc). |
| 318 | If you must use locks, |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 319 | [here](https://www.chromium.org/developers/lock-and-condition-variable) are some |
| 320 | best practices and pitfalls to avoid. |
| 321 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 322 | In order to write non-blocking code, many APIs in Chrome are asynchronous. |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 323 | Usually this means that they either need to be executed on a particular |
| 324 | thread/sequence and will return results via a custom delegate interface, or they |
| 325 | take a `base::Callback<>` object that is called when the requested operation is |
| 326 | completed. Executing work on a specific thread/sequence is covered in the |
| 327 | PostTask sections above. |
| 328 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 329 | ## Posting Multiple Tasks to the Same Thread |
| 330 | |
| 331 | 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] | 332 | [`base::SingleThreadTaskRunner`](https://cs.chromium.org/chromium/src/base/single_thread_task_runner.h). |
| 333 | All tasks posted to the same `base::SingleThreadTaskRunner` run on the same thread in |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 334 | posting order. |
| 335 | |
| 336 | ### Posting to the Main Thread or to the IO Thread in the Browser Process |
| 337 | |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 338 | To post tasks to the main thread or to the IO thread, use |
Sami Kyostila | 831c60b | 2019-07-31 13:31:23 | [diff] [blame] | 339 | `base::PostTask()` or get the appropriate SingleThreadTaskRunner using |
| 340 | `base::CreateSingleThreadTaskRunner`, supplying a `BrowserThread::ID` |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 341 | as trait. For this, you'll also need to include |
| 342 | [`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] | 343 | |
| 344 | ```cpp |
Sami Kyostila | 831c60b | 2019-07-31 13:31:23 | [diff] [blame] | 345 | base::PostTask(FROM_HERE, {content::BrowserThread::UI}, ...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 346 | |
Sami Kyostila | 831c60b | 2019-07-31 13:31:23 | [diff] [blame] | 347 | base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 348 | ->PostTask(FROM_HERE, ...); |
| 349 | ``` |
| 350 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 351 | Note: This API will soon be updated to follow the API-as-a-destination design |
| 352 | for [task APIs v3], stay tuned! |
| 353 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 354 | The main thread and the IO thread are already super busy. Therefore, prefer |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 355 | posting to a general purpose thread when possible (ref. |
| 356 | [Posting a Parallel Task](#Posting-a-Parallel-Task), |
| 357 | [Posting a Sequenced task](#Posting-a-Sequenced-Task)). |
| 358 | Good reasons to post to the main thread are to update the UI or access objects |
| 359 | that are bound to it (e.g. `Profile`). A good reason to post to the IO thread is |
| 360 | to access the internals of components that are bound to it (e.g. IPCs, network). |
| 361 | Note: It is not necessary to have an explicit post task to the IO thread to |
| 362 | send/receive an IPC or send/receive data on the network. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 363 | |
| 364 | ### Posting to the Main Thread in a Renderer Process |
| 365 | TODO |
| 366 | |
| 367 | ### Posting to a Custom SingleThreadTaskRunner |
| 368 | |
| 369 | If multiple tasks need to run on the same thread and that thread doesn’t have to |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 370 | be the main thread or the IO thread, post them to a |
| 371 | `base::SingleThreadTaskRunner` created by `base::Threadpool::CreateSingleThreadTaskRunner`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 372 | |
| 373 | ```cpp |
Dominic Farolino | dbe9769b | 2019-05-31 04:06:03 | [diff] [blame] | 374 | scoped_refptr<SingleThreadTaskRunner> single_thread_task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 375 | base::Threadpool::CreateSingleThreadTaskRunner(...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 376 | |
| 377 | // TaskB runs after TaskA completes. Both tasks run on the same thread. |
| 378 | single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA)); |
| 379 | single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB)); |
| 380 | ``` |
| 381 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 382 | Remember that we [prefer sequences to physical |
| 383 | threads](#prefer-sequences-to-physical-threads) and that this thus should rarely |
| 384 | be necessary. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 385 | |
Alexander Timin | e653dfc | 2020-01-07 17:55:06 | [diff] [blame] | 386 | ### Posting to the Current Thread |
| 387 | |
| 388 | *** note |
| 389 | **IMPORTANT:** To post a task that needs mutual exclusion with the current |
| 390 | sequence of tasks but doesn’t absolutely need to run on the current physical thread, |
| 391 | use `base::SequencedTaskRunnerHandle::Get()` instead of |
| 392 | `base::ThreadTaskRunnerHandle::Get()` (ref. [Posting to the Current |
| 393 | Sequence](#Posting-to-the-Current-Virtual_Thread)). That will better document the |
| 394 | requirements of the posted task and will avoid unnecessarily making your API |
| 395 | physical thread-affine. In a single-thread task, `base::SequencedTaskRunnerHandle::Get()` |
| 396 | is equivalent to `base::ThreadTaskRunnerHandle::Get()`. |
| 397 | *** |
| 398 | |
| 399 | If you must post a task to the current physical thread nonetheless, use |
| 400 | [`base::ThreadTaskRunnerHandle`](https://cs.chromium.org/chromium/src/base/threading/thread_task_runner_handle.h). |
| 401 | |
| 402 | ```cpp |
| 403 | // The task will run on the current thread in the future. |
| 404 | base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 405 | FROM_HERE, base::BindOnce(&Task)); |
| 406 | ``` |
| 407 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 408 | ## Posting Tasks to a COM Single-Thread Apartment (STA) Thread (Windows) |
| 409 | |
| 410 | 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] | 411 | posted to a `base::SingleThreadTaskRunner` returned by |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 412 | `base::ThreadPool::CreateCOMSTATaskRunner()`. As mentioned in [Posting Multiple |
| 413 | Tasks to the Same Thread](#Posting-Multiple-Tasks-to-the-Same-Thread), all tasks |
| 414 | posted to the same `base::SingleThreadTaskRunner` run on the same thread in |
| 415 | posting order. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 416 | |
| 417 | ```cpp |
| 418 | // Task(A|B|C)UsingCOMSTA will run on the same COM STA thread. |
| 419 | |
| 420 | void TaskAUsingCOMSTA() { |
| 421 | // [ This runs on a COM STA thread. ] |
| 422 | |
| 423 | // Make COM STA calls. |
| 424 | // ... |
| 425 | |
| 426 | // Post another task to the current COM STA thread. |
| 427 | base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 428 | FROM_HERE, base::BindOnce(&TaskCUsingCOMSTA)); |
| 429 | } |
| 430 | void TaskBUsingCOMSTA() { } |
| 431 | void TaskCUsingCOMSTA() { } |
| 432 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 433 | auto com_sta_task_runner = base::ThreadPool::CreateCOMSTATaskRunner(...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 434 | com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskAUsingCOMSTA)); |
| 435 | com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskBUsingCOMSTA)); |
| 436 | ``` |
| 437 | |
| 438 | ## Annotating Tasks with TaskTraits |
| 439 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 440 | [`base::TaskTraits`](https://cs.chromium.org/chromium/src/base/task/task_traits.h) |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 441 | encapsulate information about a task that helps the thread pool make better |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 442 | scheduling decisions. |
| 443 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 444 | Methods that take `base::TaskTraits` can be be passed `{}` when default traits |
| 445 | are sufficient. Default traits are appropriate for tasks that: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 446 | - Don’t block (ref. MayBlock and WithBaseSyncPrimitives). |
| 447 | - Prefer inheriting the current priority to specifying their own. |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 448 | - Can either block shutdown or be skipped on shutdown (thread pool is free to |
| 449 | choose a fitting default). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 450 | Tasks that don’t match this description must be posted with explicit TaskTraits. |
| 451 | |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 452 | [`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] | 453 | provides exhaustive documentation of available traits. The content layer also |
| 454 | provides additional traits in |
| 455 | [`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h) |
| 456 | to facilitate posting a task onto a BrowserThread. |
| 457 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 458 | Below are some examples of how to specify `base::TaskTraits`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 459 | |
| 460 | ```cpp |
| 461 | // This task has no explicit TaskTraits. It cannot block. Its priority |
| 462 | // is inherited from the calling context (e.g. if it is posted from |
Gabriel Charette | 141a44258 | 2018-07-27 21:23:25 | [diff] [blame] | 463 | // a BEST_EFFORT task, it will have a BEST_EFFORT priority). It will either |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 464 | // block shutdown or be skipped on shutdown. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 465 | base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(...)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 466 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 467 | // This task has the highest priority. The thread pool will try to |
Gabriel Charette | 141a44258 | 2018-07-27 21:23:25 | [diff] [blame] | 468 | // run it before USER_VISIBLE and BEST_EFFORT tasks. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 469 | base::ThreadPool::PostTask( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 470 | FROM_HERE, {base::TaskPriority::USER_BLOCKING}, |
| 471 | base::BindOnce(...)); |
| 472 | |
| 473 | // This task has the lowest priority and is allowed to block (e.g. it |
| 474 | // can read a file from disk). |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 475 | base::ThreadPool::PostTask( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 476 | FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 477 | base::BindOnce(...)); |
| 478 | |
| 479 | // This task blocks shutdown. The process won't exit before its |
| 480 | // execution is complete. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 481 | base::ThreadPool::PostTask( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 482 | FROM_HERE, {base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, |
| 483 | base::BindOnce(...)); |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 484 | |
| 485 | // This task will run on the Browser UI thread. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 486 | base::ThreadPool::PostTask( |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 487 | FROM_HERE, {content::BrowserThread::UI}, |
| 488 | base::BindOnce(...)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 489 | ``` |
| 490 | |
| 491 | ## Keeping the Browser Responsive |
| 492 | |
| 493 | Do not perform expensive work on the main thread, the IO thread or any sequence |
| 494 | that is expected to run tasks with a low latency. Instead, perform expensive |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 495 | work asynchronously using `base::ThreadPool::PostTaskAndReply*()` or |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 496 | `base::SequencedTaskRunner::PostTaskAndReply()`. Note that |
| 497 | asynchronous/overlapped I/O on the IO thread are fine. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 498 | |
| 499 | Example: Running the code below on the main thread will prevent the browser from |
| 500 | responding to user input for a long time. |
| 501 | |
| 502 | ```cpp |
| 503 | // GetHistoryItemsFromDisk() may block for a long time. |
| 504 | // AddHistoryItemsToOmniboxDropDown() updates the UI and therefore must |
| 505 | // be called on the main thread. |
| 506 | AddHistoryItemsToOmniboxDropdown(GetHistoryItemsFromDisk("keyword")); |
| 507 | ``` |
| 508 | |
| 509 | The code below solves the problem by scheduling a call to |
| 510 | `GetHistoryItemsFromDisk()` in a thread pool followed by a call to |
| 511 | `AddHistoryItemsToOmniboxDropdown()` on the origin sequence (the main thread in |
| 512 | this case). The return value of the first call is automatically provided as |
| 513 | argument to the second call. |
| 514 | |
| 515 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 516 | base::ThreadPool::PostTaskAndReplyWithResult( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 517 | FROM_HERE, {base::MayBlock()}, |
| 518 | base::BindOnce(&GetHistoryItemsFromDisk, "keyword"), |
| 519 | base::BindOnce(&AddHistoryItemsToOmniboxDropdown)); |
| 520 | ``` |
| 521 | |
| 522 | ## Posting a Task with a Delay |
| 523 | |
| 524 | ### Posting a One-Off Task with a Delay |
| 525 | |
| 526 | To post a task that must run once after a delay expires, use |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 527 | `base::ThreadPool::PostDelayedTask*()` or `base::TaskRunner::PostDelayedTask()`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 528 | |
| 529 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 530 | base::ThreadPool::PostDelayedTask( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 531 | FROM_HERE, {base::TaskPriority::BEST_EFFORT}, base::BindOnce(&Task), |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 532 | base::TimeDelta::FromHours(1)); |
| 533 | |
| 534 | scoped_refptr<base::SequencedTaskRunner> task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 535 | base::ThreadPool::CreateSequencedTaskRunner( |
| 536 | {base::TaskPriority::BEST_EFFORT}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 537 | task_runner->PostDelayedTask( |
| 538 | FROM_HERE, base::BindOnce(&Task), base::TimeDelta::FromHours(1)); |
| 539 | ``` |
| 540 | |
| 541 | *** note |
| 542 | **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] | 543 | when its delay expires. Specify `base::TaskPriority::BEST_EFFORT` to prevent it |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 544 | from slowing down the browser when its delay expires. |
| 545 | *** |
| 546 | |
| 547 | ### Posting a Repeating Task with a Delay |
| 548 | To post a task that must run at regular intervals, |
| 549 | use [`base::RepeatingTimer`](https://cs.chromium.org/chromium/src/base/timer/timer.h). |
| 550 | |
| 551 | ```cpp |
| 552 | class A { |
| 553 | public: |
| 554 | ~A() { |
| 555 | // The timer is stopped automatically when it is deleted. |
| 556 | } |
| 557 | void StartDoingStuff() { |
| 558 | timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1), |
| 559 | this, &MyClass::DoStuff); |
| 560 | } |
| 561 | void StopDoingStuff() { |
| 562 | timer_.Stop(); |
| 563 | } |
| 564 | private: |
| 565 | void DoStuff() { |
| 566 | // This method is called every second on the sequence that invoked |
| 567 | // StartDoingStuff(). |
| 568 | } |
| 569 | base::RepeatingTimer timer_; |
| 570 | }; |
| 571 | ``` |
| 572 | |
| 573 | ## Cancelling a Task |
| 574 | |
| 575 | ### Using base::WeakPtr |
| 576 | |
| 577 | [`base::WeakPtr`](https://cs.chromium.org/chromium/src/base/memory/weak_ptr.h) |
| 578 | can be used to ensure that any callback bound to an object is canceled when that |
| 579 | object is destroyed. |
| 580 | |
| 581 | ```cpp |
| 582 | int Compute() { … } |
| 583 | |
| 584 | class A { |
| 585 | public: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 586 | void ComputeAndStore() { |
| 587 | // Schedule a call to Compute() in a thread pool followed by |
| 588 | // a call to A::Store() on the current sequence. The call to |
| 589 | // A::Store() is canceled when |weak_ptr_factory_| is destroyed. |
| 590 | // (guarantees that |this| will not be used-after-free). |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 591 | base::ThreadPool::PostTaskAndReplyWithResult( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 592 | FROM_HERE, base::BindOnce(&Compute), |
| 593 | base::BindOnce(&A::Store, weak_ptr_factory_.GetWeakPtr())); |
| 594 | } |
| 595 | |
| 596 | private: |
| 597 | void Store(int value) { value_ = value; } |
| 598 | |
| 599 | int value_; |
Jeremy Roman | 0dd0b2f | 2019-07-16 21:00:43 | [diff] [blame] | 600 | base::WeakPtrFactory<A> weak_ptr_factory_{this}; |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 601 | }; |
| 602 | ``` |
| 603 | |
| 604 | Note: `WeakPtr` is not thread-safe: `GetWeakPtr()`, `~WeakPtrFactory()`, and |
| 605 | `Compute()` (bound to a `WeakPtr`) must all run on the same sequence. |
| 606 | |
| 607 | ### Using base::CancelableTaskTracker |
| 608 | |
| 609 | [`base::CancelableTaskTracker`](https://cs.chromium.org/chromium/src/base/task/cancelable_task_tracker.h) |
| 610 | allows cancellation to happen on a different sequence than the one on which |
| 611 | tasks run. Keep in mind that `CancelableTaskTracker` cannot cancel tasks that |
| 612 | have already started to run. |
| 613 | |
| 614 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 615 | auto task_runner = base::ThreadPool::CreateTaskRunner({}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 616 | base::CancelableTaskTracker cancelable_task_tracker; |
| 617 | cancelable_task_tracker.PostTask(task_runner.get(), FROM_HERE, |
Peter Kasting | 341e1fb | 2018-02-24 00:03:01 | [diff] [blame] | 618 | base::DoNothing()); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 619 | // Cancels Task(), only if it hasn't already started running. |
| 620 | cancelable_task_tracker.TryCancelAll(); |
| 621 | ``` |
| 622 | |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 623 | ## Posting a Job to run in parallel |
| 624 | |
| 625 | The [`base::PostJob`](https://cs.chromium.org/chromium/src/base/task/post_job.h) |
| 626 | is a power user API to be able to schedule a single base::RepeatingCallback |
| 627 | worker task and request that ThreadPool workers invoke it concurrently. |
| 628 | This avoids degenerate cases: |
| 629 | * Calling `PostTask()` for each work item, causing significant overhead. |
| 630 | * Fixed number of `PostTask()` calls that split the work and might run for a |
| 631 | long time. This is problematic when many components post “num cores” tasks and |
| 632 | all expect to use all the cores. In these cases, the scheduler lacks context |
| 633 | to be fair to multiple same-priority requests and/or ability to request lower |
| 634 | priority work to yield when high priority work comes in. |
| 635 | |
| 636 | ```cpp |
| 637 | // A canonical implementation of |worker_task|. |
| 638 | void WorkerTask(base::JobDelegate* job_delegate) { |
| 639 | while (!job_delegate->ShouldYield()) { |
| 640 | auto work_item = TakeWorkItem(); // Smallest unit of work. |
| 641 | if (!work_item) |
| 642 | return: |
| 643 | ProcessWork(work_item); |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | // Returns the latest thread-safe number of incomplete work items. |
| 648 | void NumIncompleteWorkItems(); |
| 649 | |
| 650 | base::PostJob(FROM_HERE, |
| 651 | {base::ThreadPool()}, |
| 652 | base::BindRepeating(&WorkerTask), |
| 653 | base::BindRepeating(&NumIncompleteWorkItems)); |
| 654 | ``` |
| 655 | |
| 656 | By doing as much work as possible in a loop when invoked, the worker task avoids |
| 657 | scheduling overhead. Meanwhile `base::JobDelegate::ShouldYield()` is |
| 658 | periodically invoked to conditionally exit and let the scheduler prioritize |
| 659 | other work. This yield-semantic allows, for example, a user-visible job to use |
| 660 | all cores but get out of the way when a user-blocking task comes in. |
| 661 | |
| 662 | ### Adding additional work to a running job. |
| 663 | |
| 664 | When new work items are added and the API user wants additional threads to |
| 665 | invoke the worker task concurrently, |
| 666 | `JobHandle/JobDelegate::NotifyConcurrencyIncrease()` *must* be invoked shortly |
| 667 | after max concurrency increases. |
| 668 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 669 | ## Testing |
| 670 | |
Gabriel Charette | 0b20ee6 | 2019-09-18 14:06:12 | [diff] [blame] | 671 | For more details see [Testing Components Which Post |
| 672 | Tasks](threading_and_tasks_testing.md). |
| 673 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 674 | To test code that uses `base::ThreadTaskRunnerHandle`, |
| 675 | `base::SequencedTaskRunnerHandle` or a function in |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 676 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h), |
| 677 | instantiate a |
Gabriel Charette | 0b20ee6 | 2019-09-18 14:06:12 | [diff] [blame] | 678 | [`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] | 679 | for the scope of the test. If you need BrowserThreads, use |
Gabriel Charette | 798fde7 | 2019-08-20 22:24:04 | [diff] [blame] | 680 | `content::BrowserTaskEnvironment` instead of |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 681 | `base::test::TaskEnvironment`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 682 | |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 683 | Tests can run the `base::test::TaskEnvironment`'s message pump using a |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 684 | `base::RunLoop`, which can be made to run until `Quit()` (explicitly or via |
| 685 | `RunLoop::QuitClosure()`), or to `RunUntilIdle()` ready-to-run tasks and |
| 686 | immediately return. |
Wez | d9e4cb77 | 2019-01-09 03:07:03 | [diff] [blame] | 687 | |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 688 | TaskEnvironment configures RunLoop::Run() to LOG(FATAL) if it hasn't been |
Wez | d9e4cb77 | 2019-01-09 03:07:03 | [diff] [blame] | 689 | explicitly quit after TestTimeouts::action_timeout(). This is preferable to |
| 690 | having the test hang if the code under test fails to trigger the RunLoop to |
| 691 | quit. The timeout can be overridden with ScopedRunTimeoutForTest. |
| 692 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 693 | ```cpp |
| 694 | class MyTest : public testing::Test { |
| 695 | public: |
| 696 | // ... |
| 697 | protected: |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 698 | base::test::TaskEnvironment task_environment_; |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 699 | }; |
| 700 | |
| 701 | TEST(MyTest, MyTest) { |
| 702 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&A)); |
| 703 | base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, |
| 704 | base::BindOnce(&B)); |
| 705 | base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( |
| 706 | FROM_HERE, base::BindOnce(&C), base::TimeDelta::Max()); |
| 707 | |
| 708 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until it is empty. |
| 709 | // Delayed tasks are not added to the queue until they are ripe for execution. |
| 710 | base::RunLoop().RunUntilIdle(); |
| 711 | // A and B have been executed. C is not ripe for execution yet. |
| 712 | |
| 713 | base::RunLoop run_loop; |
| 714 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&D)); |
| 715 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); |
| 716 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&E)); |
| 717 | |
| 718 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until QuitClosure is |
| 719 | // invoked. |
| 720 | run_loop.Run(); |
| 721 | // D and run_loop.QuitClosure() have been executed. E is still in the queue. |
| 722 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 723 | // Tasks posted to thread pool run asynchronously as they are posted. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 724 | base::ThreadPool::PostTask(FROM_HERE, {}, base::BindOnce(&F)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 725 | auto task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 726 | base::ThreadPool::CreateSequencedTaskRunner({}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 727 | task_runner->PostTask(FROM_HERE, base::BindOnce(&G)); |
| 728 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 729 | // To block until all tasks posted to thread pool are done running: |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 730 | base::ThreadPoolInstance::Get()->FlushForTesting(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 731 | // F and G have been executed. |
| 732 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 733 | base::ThreadPool::PostTaskAndReplyWithResult( |
| 734 | FROM_HERE, {}, base::BindOnce(&H), base::BindOnce(&I)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 735 | |
| 736 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until both the |
| 737 | // (Thread|Sequenced)TaskRunnerHandle queue and the TaskSchedule queue are |
| 738 | // empty: |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 739 | task_environment_.RunUntilIdle(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 740 | // E, H, I have been executed. |
| 741 | } |
| 742 | ``` |
| 743 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 744 | ## Using ThreadPool in a New Process |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 745 | |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 746 | ThreadPoolInstance needs to be initialized in a process before the functions in |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 747 | [`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] | 748 | can be used. Initialization of ThreadPoolInstance in the Chrome browser process |
| 749 | and child processes (renderer, GPU, utility) has already been taken care of. To |
| 750 | use ThreadPoolInstance in another process, initialize ThreadPoolInstance early |
| 751 | in the main function: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 752 | |
| 753 | ```cpp |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 754 | // This initializes and starts ThreadPoolInstance with default params. |
| 755 | base::ThreadPoolInstance::CreateAndStartWithDefaultParams(“process_name”); |
| 756 | // The base/task/post_task.h API can now be used with base::ThreadPool trait. |
| 757 | // Tasks will be // scheduled as they are posted. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 758 | |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 759 | // This initializes ThreadPoolInstance. |
| 760 | base::ThreadPoolInstance::Create(“process_name”); |
| 761 | // The base/task/post_task.h API can now be used with base::ThreadPool trait. No |
| 762 | // threads will be created and no tasks will be scheduled until after Start() is |
| 763 | // called. |
| 764 | base::ThreadPoolInstance::Get()->Start(params); |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 765 | // ThreadPool can now create threads and schedule tasks. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 766 | ``` |
| 767 | |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 768 | And shutdown ThreadPoolInstance late in the main function: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 769 | |
| 770 | ```cpp |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 771 | base::ThreadPoolInstance::Get()->Shutdown(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 772 | // Tasks posted with TaskShutdownBehavior::BLOCK_SHUTDOWN and |
| 773 | // tasks posted with TaskShutdownBehavior::SKIP_ON_SHUTDOWN that |
| 774 | // have started to run before the Shutdown() call have now completed their |
| 775 | // execution. Tasks posted with |
| 776 | // TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN may still be |
| 777 | // running. |
| 778 | ``` |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 779 | ## TaskRunner ownership (encourage no dependency injection) |
Sebastien Marchand | c95489b | 2017-05-25 16:39:34 | [diff] [blame] | 780 | |
| 781 | TaskRunners shouldn't be passed through several components. Instead, the |
| 782 | components that uses a TaskRunner should be the one that creates it. |
| 783 | |
| 784 | See [this example](https://codereview.chromium.org/2885173002/) of a |
| 785 | refactoring where a TaskRunner was passed through a lot of components only to be |
| 786 | used in an eventual leaf. The leaf can and should now obtain its TaskRunner |
| 787 | directly from |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 788 | [`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] | 789 | |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 790 | As mentioned above, `base::test::TaskEnvironment` allows unit tests to |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 791 | control tasks posted from underlying TaskRunners. In rare cases where a test |
| 792 | needs to more precisely control task ordering: dependency injection of |
| 793 | TaskRunners can be useful. For such cases the preferred approach is the |
| 794 | following: |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 795 | |
| 796 | ```cpp |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 797 | class Foo { |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 798 | public: |
| 799 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 800 | // Overrides |background_task_runner_| in tests. |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 801 | void SetBackgroundTaskRunnerForTesting( |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 802 | scoped_refptr<base::SequencedTaskRunner> background_task_runner) { |
| 803 | background_task_runner_ = std::move(background_task_runner); |
| 804 | } |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 805 | |
| 806 | private: |
michaelpg | 12c0457 | 2017-06-26 23:25:06 | [diff] [blame] | 807 | scoped_refptr<base::SequencedTaskRunner> background_task_runner_ = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 808 | base::ThreadPool::CreateSequencedTaskRunner( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 809 | {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 810 | } |
| 811 | ``` |
| 812 | |
| 813 | Note that this still allows removing all layers of plumbing between //chrome and |
| 814 | that component since unit tests will use the leaf layer directly. |
Gabriel Charette | 8917f4c | 2018-11-22 15:50:28 | [diff] [blame] | 815 | |
| 816 | ## FAQ |
| 817 | See [Threading and Tasks FAQ](threading_and_tasks_faq.md) for more examples. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame^] | 818 | |
| 819 | [task APIs v3]: https://docs.google.com/document/d/1tssusPykvx3g0gvbvU4HxGyn3MjJlIylnsH13-Tv6s4/edit?ts=5de99a52#heading=h.ss4tw38hvh3s |