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 |
Matt Falkenhagen | 72a2dfc | 2021-08-05 22:36:13 | [diff] [blame] | 14 | thread (a.k.a. "UI" thread in the browser process) and IO thread (each process's |
| 15 | thread for receiving |
| 16 | [IPC](https://en.wikipedia.org/wiki/Inter-process_communication)) |
| 17 | responsive. This means offloading any blocking I/O or other expensive |
| 18 | operations to other threads. Our approach is to use message passing as the way |
| 19 | of communicating between threads. We discourage locking and thread-safe objects. |
| 20 | Instead, objects live on only one (often virtual -- we'll get to that later!) |
| 21 | thread and we pass messages between those threads for communication. Absent |
| 22 | external requirements about latency or workload, Chrome attempts to be a [highly |
| 23 | concurrent, but not necessarily |
| 24 | parallel](https://stackoverflow.com/questions/1050222/what-is-the-difference-between-concurrency-and-parallelism#:~:text=Concurrency%20is%20when%20two%20or,e.g.%2C%20on%20a%20multicore%20processor.), |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 25 | system. |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 26 | |
cfredric | ff6d86c | 2022-02-15 16:26:11 | [diff] [blame^] | 27 | A basic intro to the way Chromium does concurrency (especially Sequences) can be |
| 28 | found |
| 29 | [here](https://docs.google.com/presentation/d/1ujV8LjIUyPBmULzdT2aT9Izte8PDwbJi). |
| 30 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 31 | This documentation assumes familiarity with computer science |
| 32 | [threading concepts](https://en.wikipedia.org/wiki/Thread_(computing)). |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 33 | |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 34 | ### Nomenclature |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 35 | |
| 36 | ## Core Concepts |
| 37 | * **Task**: A unit of work to be processed. Effectively a function pointer with |
Alex St-Onge | 490a97a | 2021-02-04 02:47:19 | [diff] [blame] | 38 | optionally associated state. In Chrome this is `base::OnceCallback` and |
| 39 | `base::RepeatingCallback` created via `base::BindOnce` and |
| 40 | `base::BindRepeating`, respectively. |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 41 | ([documentation](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/callback.md)). |
| 42 | * **Task queue**: A queue of tasks to be processed. |
| 43 | * **Physical thread**: An operating system provided thread (e.g. pthread on |
| 44 | POSIX or CreateThread() on Windows). The Chrome cross-platform abstraction |
| 45 | is `base::PlatformThread`. You should pretty much never use this directly. |
| 46 | * **`base::Thread`**: A physical thread forever processing messages from a |
| 47 | dedicated task queue until Quit(). You should pretty much never be creating |
| 48 | your own `base::Thread`'s. |
| 49 | * **Thread pool**: A pool of physical threads with a shared task queue. In |
Gabriel Charette | 0b20ee6 | 2019-09-18 14:06:12 | [diff] [blame] | 50 | Chrome, this is `base::ThreadPoolInstance`. There's exactly one instance per |
| 51 | Chrome process, it serves tasks posted through |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 52 | [`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] | 53 | and as such you should rarely need to use the `base::ThreadPoolInstance` API |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 54 | directly (more on posting tasks later). |
| 55 | * **Sequence** or **Virtual thread**: A chrome-managed thread of execution. |
| 56 | Like a physical thread, only one task can run on a given sequence / virtual |
| 57 | thread at any given moment and each task sees the side-effects of the |
| 58 | preceding tasks. Tasks are executed sequentially but may hop physical |
| 59 | threads between each one. |
| 60 | * **Task runner**: An interface through which tasks can be posted. In Chrome |
| 61 | this is `base::TaskRunner`. |
| 62 | * **Sequenced task runner**: A task runner which guarantees that tasks posted |
| 63 | to it will run sequentially, in posted order. Each such task is guaranteed to |
| 64 | see the side-effects of the task preceding it. Tasks posted to a sequenced |
| 65 | task runner are typically processed by a single thread (virtual or physical). |
| 66 | In Chrome this is `base::SequencedTaskRunner` which is-a |
| 67 | `base::TaskRunner`. |
| 68 | * **Single-thread task runner**: A sequenced task runner which guarantees that |
| 69 | all tasks will be processed by the same physical thread. In Chrome this is |
| 70 | `base::SingleThreadTaskRunner` which is-a `base::SequencedTaskRunner`. We |
| 71 | [prefer sequences to threads](#prefer-sequences-to-physical-threads) whenever |
| 72 | possible. |
| 73 | |
| 74 | ## Threading Lexicon |
| 75 | Note to the reader: the following terms are an attempt to bridge the gap between |
| 76 | common threading nomenclature and the way we use them in Chrome. It might be a |
| 77 | bit heavy if you're just getting started. Should this be hard to parse, consider |
| 78 | skipping to the more detailed sections below and referring back to this as |
| 79 | necessary. |
| 80 | |
| 81 | * **Thread-unsafe**: The vast majority of types in Chrome are thread-unsafe |
| 82 | (by design). Access to such types/methods must be externally synchronized. |
| 83 | Typically thread-unsafe types require that all tasks accessing their state be |
| 84 | posted to the same `base::SequencedTaskRunner` and they verify this in debug |
| 85 | builds with a `SEQUENCE_CHECKER` member. Locks are also an option to |
| 86 | synchronize access but in Chrome we strongly |
| 87 | [prefer sequences to locks](#Using-Sequences-Instead-of-Locks). |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 88 | * **Thread-affine**: Such types/methods need to be always accessed from the |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 89 | same physical thread (i.e. from the same `base::SingleThreadTaskRunner`) and |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 90 | typically have a `THREAD_CHECKER` member to verify that they are. Short of |
| 91 | using a third-party API or having a leaf dependency which is thread-affine: |
| 92 | there's pretty much no reason for a type to be thread-affine in Chrome. |
| 93 | Note that `base::SingleThreadTaskRunner` is-a `base::SequencedTaskRunner` so |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 94 | thread-affine is a subset of thread-unsafe. Thread-affine is also sometimes |
| 95 | referred to as **thread-hostile**. |
Albert J. Wong | f06ff500 | 2021-07-08 20:37:00 | [diff] [blame] | 96 | * **Thread-safe**: Such types/methods can be safely accessed in parallel. |
| 97 | * **Thread-compatible**: Such types provide safe parallel access to const |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 98 | methods but require synchronization for non-const (or mixed const/non-const |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 99 | access). Chrome doesn't expose reader-writer locks; as such, the only use |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 100 | case for this is objects (typically globals) which are initialized once in a |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 101 | thread-safe manner (either in the single-threaded phase of startup or lazily |
| 102 | through a thread-safe static-local-initialization paradigm a la |
Gabriel Charette | b984d67 | 2019-02-12 21:53:27 | [diff] [blame] | 103 | `base::NoDestructor`) and forever after immutable. |
| 104 | * **Immutable**: A subset of thread-compatible types which cannot be modified |
| 105 | after construction. |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 106 | * **Sequence-friendly**: Such types/methods are thread-unsafe types which |
| 107 | support being invoked from a `base::SequencedTaskRunner`. Ideally this would |
| 108 | be the case for all thread-unsafe types but legacy code sometimes has |
| 109 | overzealous checks that enforce thread-affinity in mere thread-unsafe |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 110 | scenarios. See [Prefer Sequences to |
| 111 | Threads](#prefer-sequences-to-physical-threads) below for more details. |
Gabriel Charette | 364a16a | 2019-02-06 21:12:15 | [diff] [blame] | 112 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 113 | ### Threads |
| 114 | |
| 115 | Every Chrome process has |
| 116 | |
| 117 | * a main thread |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 118 | * in the browser process (BrowserThread::UI): updates the UI |
| 119 | * in renderer processes (Blink main thread): runs most of Blink |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 120 | * an IO thread |
Matt Falkenhagen | 72a2dfc | 2021-08-05 22:36:13 | [diff] [blame] | 121 | * in all processes: all IPC messages arrive on this thread. The application |
| 122 | logic to handle the message may be in a different thread (i.e., the IO |
| 123 | thread may route the message to a [Mojo |
| 124 | interface](/docs/README.md#Mojo-Services) which is bound to a |
| 125 | different thread). |
| 126 | * more generally most async I/O happens on this thread (e.g., through |
| 127 | base::FileDescriptorWatcher). |
| 128 | * in the browser process: this is called BrowserThread::IO. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 129 | * a few more special-purpose threads |
| 130 | * and a pool of general-purpose threads |
| 131 | |
| 132 | Most threads have a loop that gets tasks from a queue and runs them (the queue |
| 133 | may be shared between multiple threads). |
| 134 | |
| 135 | ### Tasks |
| 136 | |
| 137 | A task is a `base::OnceClosure` added to a queue for asynchronous execution. |
| 138 | |
| 139 | A `base::OnceClosure` stores a function pointer and arguments. It has a `Run()` |
| 140 | method that invokes the function pointer using the bound arguments. It is |
| 141 | created using `base::BindOnce`. (ref. [Callback<> and Bind() |
| 142 | documentation](callback.md)). |
| 143 | |
| 144 | ``` |
| 145 | void TaskA() {} |
| 146 | void TaskB(int v) {} |
| 147 | |
| 148 | auto task_a = base::BindOnce(&TaskA); |
| 149 | auto task_b = base::BindOnce(&TaskB, 42); |
| 150 | ``` |
| 151 | |
| 152 | A group of tasks can be executed in one of the following ways: |
| 153 | |
| 154 | * [Parallel](#Posting-a-Parallel-Task): No task execution ordering, possibly all |
| 155 | at once on any thread |
| 156 | * [Sequenced](#Posting-a-Sequenced-Task): Tasks executed in posting order, one |
| 157 | at a time on any thread. |
| 158 | * [Single Threaded](#Posting-Multiple-Tasks-to-the-Same-Thread): Tasks executed |
| 159 | in posting order, one at a time on a single thread. |
Drew Stonebraker | 653a3ba | 2019-07-02 19:24:23 | [diff] [blame] | 160 | * [COM Single Threaded](#Posting-Tasks-to-a-COM-Single_Thread-Apartment-STA_Thread-Windows): |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 161 | A variant of single threaded with COM initialized. |
| 162 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 163 | ### Prefer Sequences to Physical Threads |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 164 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 165 | Sequenced execution (on virtual threads) is strongly preferred to |
| 166 | single-threaded execution (on physical threads). Except for types/methods bound |
| 167 | to the main thread (UI) or IO threads: thread-safety is better achieved via |
| 168 | `base::SequencedTaskRunner` than through managing your own physical threads |
| 169 | (ref. [Posting a Sequenced Task](#posting-a-sequenced-task) below). |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 170 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 171 | All APIs which are exposed for "current physical thread" have an equivalent for |
| 172 | "current sequence" |
| 173 | ([mapping](threading_and_tasks_faq.md#How-to-migrate-from-SingleThreadTaskRunner-to-SequencedTaskRunner)). |
gab | 2a457605 | 2017-06-07 23:36:12 | [diff] [blame] | 174 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 175 | If you find yourself writing a sequence-friendly type and it fails |
| 176 | thread-affinity checks (e.g., `THREAD_CHECKER`) in a leaf dependency: consider |
| 177 | making that dependency sequence-friendly as well. Most core APIs in Chrome are |
| 178 | sequence-friendly, but some legacy types may still over-zealously use |
| 179 | ThreadChecker/ThreadTaskRunnerHandle/SingleThreadTaskRunner when they could |
| 180 | instead rely on the "current sequence" and no longer be thread-affine. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 181 | |
| 182 | ## Posting a Parallel Task |
| 183 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 184 | ### Direct Posting to the Thread Pool |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 185 | |
| 186 | A task that can run on any thread and doesn’t have ordering or mutual exclusion |
| 187 | requirements with other tasks should be posted using one of the |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 188 | `base::ThreadPool::PostTask*()` functions defined in |
| 189 | [`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] | 190 | |
| 191 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 192 | base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(&Task)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 193 | ``` |
| 194 | |
| 195 | This posts tasks with default traits. |
| 196 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 197 | The `base::ThreadPool::PostTask*()` functions allow the caller to provide |
| 198 | additional details about the task via TaskTraits (ref. [Annotating Tasks with |
| 199 | TaskTraits](#Annotating-Tasks-with-TaskTraits)). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 200 | |
| 201 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 202 | base::ThreadPool::PostTask( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 203 | FROM_HERE, {base::TaskPriority::BEST_EFFORT, MayBlock()}, |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 204 | base::BindOnce(&Task)); |
| 205 | ``` |
| 206 | |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 207 | ### Posting via a TaskRunner |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 208 | |
| 209 | A parallel |
Patrick Monette | 2d93ad90 | 2021-11-01 19:20:22 | [diff] [blame] | 210 | [`base::TaskRunner`](https://cs.chromium.org/chromium/src/base/task/task_runner.h) is |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 211 | an alternative to calling `base::ThreadPool::PostTask*()` directly. This is |
| 212 | mainly useful when it isn’t known in advance whether tasks will be posted in |
| 213 | parallel, in sequence, or to a single-thread (ref. [Posting a Sequenced |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 214 | Task](#Posting-a-Sequenced-Task), [Posting Multiple Tasks to the Same |
| 215 | Thread](#Posting-Multiple-Tasks-to-the-Same-Thread)). Since `base::TaskRunner` |
| 216 | is the base class of `base::SequencedTaskRunner` and |
| 217 | `base::SingleThreadTaskRunner`, a `scoped_refptr<TaskRunner>` member can hold a |
| 218 | `base::TaskRunner`, a `base::SequencedTaskRunner` or a |
| 219 | `base::SingleThreadTaskRunner`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 220 | |
| 221 | ```cpp |
| 222 | class A { |
| 223 | public: |
| 224 | A() = default; |
| 225 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 226 | void PostSomething() { |
| 227 | task_runner_->PostTask(FROM_HERE, base::BindOnce(&A, &DoSomething)); |
| 228 | } |
| 229 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 230 | void DoSomething() { |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 231 | } |
| 232 | |
| 233 | private: |
| 234 | scoped_refptr<base::TaskRunner> task_runner_ = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 235 | base::ThreadPool::CreateTaskRunner({base::TaskPriority::USER_VISIBLE}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 236 | }; |
| 237 | ``` |
| 238 | |
| 239 | Unless a test needs to control precisely how tasks are executed, it is preferred |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 240 | to call `base::ThreadPool::PostTask*()` directly (ref. [Testing](#Testing) for |
| 241 | less invasive ways of controlling tasks in tests). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 242 | |
| 243 | ## Posting a Sequenced Task |
| 244 | |
| 245 | A sequence is a set of tasks that run one at a time in posting order (not |
| 246 | necessarily on the same thread). To post tasks as part of a sequence, use a |
Patrick Monette | 2d93ad90 | 2021-11-01 19:20:22 | [diff] [blame] | 247 | [`base::SequencedTaskRunner`](https://cs.chromium.org/chromium/src/base/task/sequenced_task_runner.h). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 248 | |
| 249 | ### Posting to a New Sequence |
| 250 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 251 | A `base::SequencedTaskRunner` can be created by |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 252 | `base::ThreadPool::CreateSequencedTaskRunner()`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 253 | |
| 254 | ```cpp |
| 255 | scoped_refptr<SequencedTaskRunner> sequenced_task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 256 | base::ThreadPool::CreateSequencedTaskRunner(...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 257 | |
| 258 | // TaskB runs after TaskA completes. |
| 259 | sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA)); |
| 260 | sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB)); |
| 261 | ``` |
| 262 | |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 263 | ### Posting to the Current (Virtual) Thread |
| 264 | |
Gabriel Charette | fee5566 | 2019-11-20 21:06:28 | [diff] [blame] | 265 | The preferred way of posting to the current (virtual) thread is via |
| 266 | `base::SequencedTaskRunnerHandle::Get()`. |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 267 | |
| 268 | ```cpp |
| 269 | // The task will run on the current (virtual) thread's default task queue. |
Gabriel Charette | fee5566 | 2019-11-20 21:06:28 | [diff] [blame] | 270 | base::SequencedTaskRunnerHandle::Get()->PostTask( |
| 271 | FROM_HERE, base::BindOnce(&Task); |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 272 | ``` |
| 273 | |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 274 | Note that `SequencedTaskRunnerHandle::Get()` returns the default queue for the |
Gabriel Charette | fee5566 | 2019-11-20 21:06:28 | [diff] [blame] | 275 | current virtual thread. On threads with multiple task queues (e.g. |
| 276 | BrowserThread::UI) this can be a different queue than the one the current task |
| 277 | belongs to. The "current" task runner is intentionally not exposed via a static |
| 278 | getter. Either you know it already and can post to it directly or you don't and |
| 279 | the only sensible destination is the default queue. |
Alex Clarke | 0dd49956 | 2019-10-18 19:45:09 | [diff] [blame] | 280 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 281 | ## Using Sequences Instead of Locks |
| 282 | |
| 283 | Usage of locks is discouraged in Chrome. Sequences inherently provide |
Gabriel Charette | a3ccc97 | 2018-11-13 14:43:12 | [diff] [blame] | 284 | thread-safety. Prefer classes that are always accessed from the same |
| 285 | sequence to managing your own thread-safety with locks. |
| 286 | |
| 287 | **Thread-safe but not thread-affine; how so?** Tasks posted to the same sequence |
| 288 | will run in sequential order. After a sequenced task completes, the next task |
| 289 | may be picked up by a different worker thread, but that task is guaranteed to |
| 290 | see any side-effects caused by the previous one(s) on its sequence. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 291 | |
| 292 | ```cpp |
| 293 | class A { |
| 294 | public: |
| 295 | A() { |
| 296 | // Do not require accesses to be on the creation sequence. |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 297 | DETACH_FROM_SEQUENCE(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 298 | } |
| 299 | |
| 300 | void AddValue(int v) { |
| 301 | // Check that all accesses are on the same sequence. |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 302 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 303 | values_.push_back(v); |
| 304 | } |
| 305 | |
| 306 | private: |
isherman | 8c33b8a | 2017-06-27 19:18:30 | [diff] [blame] | 307 | SEQUENCE_CHECKER(sequence_checker_); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 308 | |
| 309 | // No lock required, because all accesses are on the |
| 310 | // same sequence. |
| 311 | std::vector<int> values_; |
| 312 | }; |
| 313 | |
| 314 | A a; |
| 315 | scoped_refptr<SequencedTaskRunner> task_runner_for_a = ...; |
Mike Bjorge | d3a0984 | 2018-05-15 18:37:28 | [diff] [blame] | 316 | task_runner_for_a->PostTask(FROM_HERE, |
| 317 | base::BindOnce(&A::AddValue, base::Unretained(&a), 42)); |
| 318 | task_runner_for_a->PostTask(FROM_HERE, |
| 319 | base::BindOnce(&A::AddValue, base::Unretained(&a), 27)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 320 | |
| 321 | // Access from a different sequence causes a DCHECK failure. |
| 322 | scoped_refptr<SequencedTaskRunner> other_task_runner = ...; |
| 323 | other_task_runner->PostTask(FROM_HERE, |
Mike Bjorge | d3a0984 | 2018-05-15 18:37:28 | [diff] [blame] | 324 | base::BindOnce(&A::AddValue, base::Unretained(&a), 1)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 325 | ``` |
| 326 | |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 327 | Locks should only be used to swap in a shared data structure that can be |
| 328 | accessed on multiple threads. If one thread updates it based on expensive |
| 329 | computation or through disk access, then that slow work should be done without |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 330 | holding the lock. Only when the result is available should the lock be used to |
| 331 | swap in the new data. An example of this is in PluginList::LoadPlugins |
| 332 | ([`content/browser/plugin_list.cc`](https://cs.chromium.org/chromium/src/content/browser/plugin_list.cc). |
| 333 | If you must use locks, |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 334 | [here](https://www.chromium.org/developers/lock-and-condition-variable) are some |
| 335 | best practices and pitfalls to avoid. |
| 336 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 337 | In order to write non-blocking code, many APIs in Chrome are asynchronous. |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 338 | Usually this means that they either need to be executed on a particular |
| 339 | thread/sequence and will return results via a custom delegate interface, or they |
Alex St-Onge | 490a97a | 2021-02-04 02:47:19 | [diff] [blame] | 340 | take a `base::OnceCallback<>` (or `base::RepeatingCallback<>`) object that is |
| 341 | called when the requested operation is completed. Executing work on a specific |
| 342 | thread/sequence is covered in the PostTask sections above. |
Gabriel Charette | 9048031 | 2018-02-16 15:10:05 | [diff] [blame] | 343 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 344 | ## Posting Multiple Tasks to the Same Thread |
| 345 | |
| 346 | If multiple tasks need to run on the same thread, post them to a |
Patrick Monette | 2d93ad90 | 2021-11-01 19:20:22 | [diff] [blame] | 347 | [`base::SingleThreadTaskRunner`](https://cs.chromium.org/chromium/src/base/task/single_thread_task_runner.h). |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 348 | All tasks posted to the same `base::SingleThreadTaskRunner` run on the same thread in |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 349 | posting order. |
| 350 | |
| 351 | ### Posting to the Main Thread or to the IO Thread in the Browser Process |
| 352 | |
Eric Seckler | 6cf08db8 | 2018-08-30 12:01:55 | [diff] [blame] | 353 | To post tasks to the main thread or to the IO thread, use |
Olivier Li | 56b99d4e | 2020-02-11 13:51:41 | [diff] [blame] | 354 | `content::GetUIThreadTaskRunner({})` or `content::GetIOThreadTaskRunner({})` |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 355 | from |
| 356 | [`content/public/browser/browser_thread.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_thread.h) |
| 357 | |
| 358 | You may provide additional BrowserTaskTraits as a parameter to those methods |
| 359 | though this is generally still uncommon in BrowserThreads and should be reserved |
| 360 | for advanced use cases. |
| 361 | |
| 362 | There's an ongoing migration ([task APIs v3]) away from the previous |
| 363 | base-API-with-traits which you may still find throughout the codebase (it's |
| 364 | equivalent): |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 365 | |
| 366 | ```cpp |
Sami Kyostila | 831c60b | 2019-07-31 13:31:23 | [diff] [blame] | 367 | base::PostTask(FROM_HERE, {content::BrowserThread::UI}, ...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 368 | |
Sami Kyostila | 831c60b | 2019-07-31 13:31:23 | [diff] [blame] | 369 | base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 370 | ->PostTask(FROM_HERE, ...); |
| 371 | ``` |
| 372 | |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 373 | Note: For the duration of the migration, you'll unfortunately need to continue |
| 374 | manually including |
| 375 | [`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h). |
| 376 | to use the browser_thread.h API. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 377 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 378 | The main thread and the IO thread are already super busy. Therefore, prefer |
fdoray | 52bf555 | 2017-05-11 12:43:59 | [diff] [blame] | 379 | posting to a general purpose thread when possible (ref. |
| 380 | [Posting a Parallel Task](#Posting-a-Parallel-Task), |
| 381 | [Posting a Sequenced task](#Posting-a-Sequenced-Task)). |
| 382 | Good reasons to post to the main thread are to update the UI or access objects |
| 383 | that are bound to it (e.g. `Profile`). A good reason to post to the IO thread is |
| 384 | to access the internals of components that are bound to it (e.g. IPCs, network). |
| 385 | Note: It is not necessary to have an explicit post task to the IO thread to |
| 386 | send/receive an IPC or send/receive data on the network. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 387 | |
| 388 | ### Posting to the Main Thread in a Renderer Process |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 389 | TODO(blink-dev) |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 390 | |
| 391 | ### Posting to a Custom SingleThreadTaskRunner |
| 392 | |
| 393 | 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] | 394 | be the main thread or the IO thread, post them to a |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 395 | `base::SingleThreadTaskRunner` created by |
| 396 | `base::Threadpool::CreateSingleThreadTaskRunner`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 397 | |
| 398 | ```cpp |
Dominic Farolino | dbe9769b | 2019-05-31 04:06:03 | [diff] [blame] | 399 | scoped_refptr<SingleThreadTaskRunner> single_thread_task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 400 | base::Threadpool::CreateSingleThreadTaskRunner(...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 401 | |
| 402 | // TaskB runs after TaskA completes. Both tasks run on the same thread. |
| 403 | single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA)); |
| 404 | single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB)); |
| 405 | ``` |
| 406 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 407 | Remember that we [prefer sequences to physical |
| 408 | threads](#prefer-sequences-to-physical-threads) and that this thus should rarely |
| 409 | be necessary. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 410 | |
Alexander Timin | e653dfc | 2020-01-07 17:55:06 | [diff] [blame] | 411 | ### Posting to the Current Thread |
| 412 | |
| 413 | *** note |
| 414 | **IMPORTANT:** To post a task that needs mutual exclusion with the current |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 415 | sequence of tasks but doesn’t absolutely need to run on the current physical |
| 416 | thread, use `base::SequencedTaskRunnerHandle::Get()` instead of |
Alexander Timin | e653dfc | 2020-01-07 17:55:06 | [diff] [blame] | 417 | `base::ThreadTaskRunnerHandle::Get()` (ref. [Posting to the Current |
Gabriel Charette | 49e3cd0 | 2020-01-28 03:45:27 | [diff] [blame] | 418 | Sequence](#Posting-to-the-Current-Virtual_Thread)). That will better document |
| 419 | the requirements of the posted task and will avoid unnecessarily making your API |
| 420 | physical thread-affine. In a single-thread task, |
| 421 | `base::SequencedTaskRunnerHandle::Get()` is equivalent to |
| 422 | `base::ThreadTaskRunnerHandle::Get()`. |
Alexander Timin | e653dfc | 2020-01-07 17:55:06 | [diff] [blame] | 423 | *** |
| 424 | |
| 425 | If you must post a task to the current physical thread nonetheless, use |
| 426 | [`base::ThreadTaskRunnerHandle`](https://cs.chromium.org/chromium/src/base/threading/thread_task_runner_handle.h). |
| 427 | |
| 428 | ```cpp |
| 429 | // The task will run on the current thread in the future. |
| 430 | base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 431 | FROM_HERE, base::BindOnce(&Task)); |
| 432 | ``` |
| 433 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 434 | ## Posting Tasks to a COM Single-Thread Apartment (STA) Thread (Windows) |
| 435 | |
| 436 | 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] | 437 | posted to a `base::SingleThreadTaskRunner` returned by |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 438 | `base::ThreadPool::CreateCOMSTATaskRunner()`. As mentioned in [Posting Multiple |
| 439 | Tasks to the Same Thread](#Posting-Multiple-Tasks-to-the-Same-Thread), all tasks |
| 440 | posted to the same `base::SingleThreadTaskRunner` run on the same thread in |
| 441 | posting order. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 442 | |
| 443 | ```cpp |
| 444 | // Task(A|B|C)UsingCOMSTA will run on the same COM STA thread. |
| 445 | |
| 446 | void TaskAUsingCOMSTA() { |
| 447 | // [ This runs on a COM STA thread. ] |
| 448 | |
| 449 | // Make COM STA calls. |
| 450 | // ... |
| 451 | |
| 452 | // Post another task to the current COM STA thread. |
| 453 | base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 454 | FROM_HERE, base::BindOnce(&TaskCUsingCOMSTA)); |
| 455 | } |
| 456 | void TaskBUsingCOMSTA() { } |
| 457 | void TaskCUsingCOMSTA() { } |
| 458 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 459 | auto com_sta_task_runner = base::ThreadPool::CreateCOMSTATaskRunner(...); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 460 | com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskAUsingCOMSTA)); |
| 461 | com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskBUsingCOMSTA)); |
| 462 | ``` |
| 463 | |
| 464 | ## Annotating Tasks with TaskTraits |
| 465 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 466 | [`base::TaskTraits`](https://cs.chromium.org/chromium/src/base/task/task_traits.h) |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 467 | encapsulate information about a task that helps the thread pool make better |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 468 | scheduling decisions. |
| 469 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 470 | Methods that take `base::TaskTraits` can be be passed `{}` when default traits |
| 471 | are sufficient. Default traits are appropriate for tasks that: |
Gabriel Charette | de41cad | 2020-03-03 18:05:06 | [diff] [blame] | 472 | - Don’t block (ref. MayBlock and WithBaseSyncPrimitives); |
| 473 | - Pertain to user-blocking activity; |
| 474 | (explicitly or implicitly by having an ordering dependency with a component |
| 475 | that does) |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 476 | - Can either block shutdown or be skipped on shutdown (thread pool is free to |
| 477 | choose a fitting default). |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 478 | Tasks that don’t match this description must be posted with explicit TaskTraits. |
| 479 | |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 480 | [`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] | 481 | provides exhaustive documentation of available traits. The content layer also |
| 482 | provides additional traits in |
| 483 | [`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h) |
| 484 | to facilitate posting a task onto a BrowserThread. |
| 485 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 486 | Below are some examples of how to specify `base::TaskTraits`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 487 | |
| 488 | ```cpp |
Gabriel Charette | de41cad | 2020-03-03 18:05:06 | [diff] [blame] | 489 | // This task has no explicit TaskTraits. It cannot block. Its priority is |
| 490 | // USER_BLOCKING. It will either block shutdown or be skipped on shutdown. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 491 | base::ThreadPool::PostTask(FROM_HERE, base::BindOnce(...)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 492 | |
Gabriel Charette | de41cad | 2020-03-03 18:05:06 | [diff] [blame] | 493 | // This task has the highest priority. The thread pool will schedule it before |
| 494 | // USER_VISIBLE and BEST_EFFORT tasks. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 495 | base::ThreadPool::PostTask( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 496 | FROM_HERE, {base::TaskPriority::USER_BLOCKING}, |
| 497 | base::BindOnce(...)); |
| 498 | |
| 499 | // This task has the lowest priority and is allowed to block (e.g. it |
| 500 | // can read a file from disk). |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 501 | base::ThreadPool::PostTask( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 502 | FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 503 | base::BindOnce(...)); |
| 504 | |
| 505 | // This task blocks shutdown. The process won't exit before its |
| 506 | // execution is complete. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 507 | base::ThreadPool::PostTask( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 508 | FROM_HERE, {base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, |
| 509 | base::BindOnce(...)); |
| 510 | ``` |
| 511 | |
| 512 | ## Keeping the Browser Responsive |
| 513 | |
| 514 | Do not perform expensive work on the main thread, the IO thread or any sequence |
| 515 | that is expected to run tasks with a low latency. Instead, perform expensive |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 516 | work asynchronously using `base::ThreadPool::PostTaskAndReply*()` or |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 517 | `base::SequencedTaskRunner::PostTaskAndReply()`. Note that |
| 518 | asynchronous/overlapped I/O on the IO thread are fine. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 519 | |
| 520 | Example: Running the code below on the main thread will prevent the browser from |
| 521 | responding to user input for a long time. |
| 522 | |
| 523 | ```cpp |
| 524 | // GetHistoryItemsFromDisk() may block for a long time. |
| 525 | // AddHistoryItemsToOmniboxDropDown() updates the UI and therefore must |
| 526 | // be called on the main thread. |
| 527 | AddHistoryItemsToOmniboxDropdown(GetHistoryItemsFromDisk("keyword")); |
| 528 | ``` |
| 529 | |
| 530 | The code below solves the problem by scheduling a call to |
| 531 | `GetHistoryItemsFromDisk()` in a thread pool followed by a call to |
| 532 | `AddHistoryItemsToOmniboxDropdown()` on the origin sequence (the main thread in |
| 533 | this case). The return value of the first call is automatically provided as |
| 534 | argument to the second call. |
| 535 | |
| 536 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 537 | base::ThreadPool::PostTaskAndReplyWithResult( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 538 | FROM_HERE, {base::MayBlock()}, |
| 539 | base::BindOnce(&GetHistoryItemsFromDisk, "keyword"), |
| 540 | base::BindOnce(&AddHistoryItemsToOmniboxDropdown)); |
| 541 | ``` |
| 542 | |
| 543 | ## Posting a Task with a Delay |
| 544 | |
| 545 | ### Posting a One-Off Task with a Delay |
| 546 | |
| 547 | To post a task that must run once after a delay expires, use |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 548 | `base::ThreadPool::PostDelayedTask*()` or `base::TaskRunner::PostDelayedTask()`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 549 | |
| 550 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 551 | base::ThreadPool::PostDelayedTask( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 552 | FROM_HERE, {base::TaskPriority::BEST_EFFORT}, base::BindOnce(&Task), |
Peter Kasting | e5a38ed | 2021-10-02 03:06:35 | [diff] [blame] | 553 | base::Hours(1)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 554 | |
| 555 | scoped_refptr<base::SequencedTaskRunner> task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 556 | base::ThreadPool::CreateSequencedTaskRunner( |
| 557 | {base::TaskPriority::BEST_EFFORT}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 558 | task_runner->PostDelayedTask( |
Peter Kasting | e5a38ed | 2021-10-02 03:06:35 | [diff] [blame] | 559 | FROM_HERE, base::BindOnce(&Task), base::Hours(1)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 560 | ``` |
| 561 | |
| 562 | *** note |
| 563 | **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] | 564 | when its delay expires. Specify `base::TaskPriority::BEST_EFFORT` to prevent it |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 565 | from slowing down the browser when its delay expires. |
| 566 | *** |
| 567 | |
| 568 | ### Posting a Repeating Task with a Delay |
| 569 | To post a task that must run at regular intervals, |
| 570 | use [`base::RepeatingTimer`](https://cs.chromium.org/chromium/src/base/timer/timer.h). |
| 571 | |
| 572 | ```cpp |
| 573 | class A { |
| 574 | public: |
| 575 | ~A() { |
| 576 | // The timer is stopped automatically when it is deleted. |
| 577 | } |
| 578 | void StartDoingStuff() { |
Peter Kasting | 53fd6ee | 2021-10-05 20:40:48 | [diff] [blame] | 579 | timer_.Start(FROM_HERE, Seconds(1), |
Erik Chen | 0ee26a3 | 2021-07-14 20:04:47 | [diff] [blame] | 580 | this, &A::DoStuff); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 581 | } |
| 582 | void StopDoingStuff() { |
| 583 | timer_.Stop(); |
| 584 | } |
| 585 | private: |
| 586 | void DoStuff() { |
| 587 | // This method is called every second on the sequence that invoked |
| 588 | // StartDoingStuff(). |
| 589 | } |
| 590 | base::RepeatingTimer timer_; |
| 591 | }; |
| 592 | ``` |
| 593 | |
| 594 | ## Cancelling a Task |
| 595 | |
| 596 | ### Using base::WeakPtr |
| 597 | |
| 598 | [`base::WeakPtr`](https://cs.chromium.org/chromium/src/base/memory/weak_ptr.h) |
| 599 | can be used to ensure that any callback bound to an object is canceled when that |
| 600 | object is destroyed. |
| 601 | |
| 602 | ```cpp |
| 603 | int Compute() { … } |
| 604 | |
| 605 | class A { |
| 606 | public: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 607 | void ComputeAndStore() { |
| 608 | // Schedule a call to Compute() in a thread pool followed by |
| 609 | // a call to A::Store() on the current sequence. The call to |
| 610 | // A::Store() is canceled when |weak_ptr_factory_| is destroyed. |
| 611 | // (guarantees that |this| will not be used-after-free). |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 612 | base::ThreadPool::PostTaskAndReplyWithResult( |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 613 | FROM_HERE, base::BindOnce(&Compute), |
| 614 | base::BindOnce(&A::Store, weak_ptr_factory_.GetWeakPtr())); |
| 615 | } |
| 616 | |
| 617 | private: |
| 618 | void Store(int value) { value_ = value; } |
| 619 | |
| 620 | int value_; |
Jeremy Roman | 0dd0b2f | 2019-07-16 21:00:43 | [diff] [blame] | 621 | base::WeakPtrFactory<A> weak_ptr_factory_{this}; |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 622 | }; |
| 623 | ``` |
| 624 | |
| 625 | Note: `WeakPtr` is not thread-safe: `GetWeakPtr()`, `~WeakPtrFactory()`, and |
Francois Doray | f652a9d0 | 2021-07-06 13:07:52 | [diff] [blame] | 626 | `Store()` (bound to a `WeakPtr`) must all run on the same sequence. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 627 | |
| 628 | ### Using base::CancelableTaskTracker |
| 629 | |
| 630 | [`base::CancelableTaskTracker`](https://cs.chromium.org/chromium/src/base/task/cancelable_task_tracker.h) |
| 631 | allows cancellation to happen on a different sequence than the one on which |
| 632 | tasks run. Keep in mind that `CancelableTaskTracker` cannot cancel tasks that |
| 633 | have already started to run. |
| 634 | |
| 635 | ```cpp |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 636 | auto task_runner = base::ThreadPool::CreateTaskRunner({}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 637 | base::CancelableTaskTracker cancelable_task_tracker; |
| 638 | cancelable_task_tracker.PostTask(task_runner.get(), FROM_HERE, |
Peter Kasting | 341e1fb | 2018-02-24 00:03:01 | [diff] [blame] | 639 | base::DoNothing()); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 640 | // Cancels Task(), only if it hasn't already started running. |
| 641 | cancelable_task_tracker.TryCancelAll(); |
| 642 | ``` |
| 643 | |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 644 | ## Posting a Job to run in parallel |
| 645 | |
| 646 | The [`base::PostJob`](https://cs.chromium.org/chromium/src/base/task/post_job.h) |
| 647 | is a power user API to be able to schedule a single base::RepeatingCallback |
Albert J. Wong | f06ff500 | 2021-07-08 20:37:00 | [diff] [blame] | 648 | worker task and request that ThreadPool workers invoke it in parallel. |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 649 | This avoids degenerate cases: |
| 650 | * Calling `PostTask()` for each work item, causing significant overhead. |
| 651 | * Fixed number of `PostTask()` calls that split the work and might run for a |
| 652 | long time. This is problematic when many components post “num cores” tasks and |
| 653 | all expect to use all the cores. In these cases, the scheduler lacks context |
| 654 | to be fair to multiple same-priority requests and/or ability to request lower |
| 655 | priority work to yield when high priority work comes in. |
| 656 | |
Etienne Pierre-doray | 6d3cd919 | 2020-04-06 21:10:37 | [diff] [blame] | 657 | See [`base/task/job_perftest.cc`](https://cs.chromium.org/chromium/src/base/task/job_perftest.cc) |
| 658 | for a complete example. |
| 659 | |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 660 | ```cpp |
| 661 | // A canonical implementation of |worker_task|. |
| 662 | void WorkerTask(base::JobDelegate* job_delegate) { |
| 663 | while (!job_delegate->ShouldYield()) { |
| 664 | auto work_item = TakeWorkItem(); // Smallest unit of work. |
| 665 | if (!work_item) |
| 666 | return: |
| 667 | ProcessWork(work_item); |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | // Returns the latest thread-safe number of incomplete work items. |
Etienne Pierre-Doray | f91d7a0 | 2020-09-11 15:53:27 | [diff] [blame] | 672 | void NumIncompleteWorkItems(size_t worker_count) { |
| 673 | // NumIncompleteWorkItems() may use |worker_count| if it needs to account for |
| 674 | // local work lists, which is easier than doing its own accounting, keeping in |
| 675 | // mind that the actual number of items may be racily overestimated and thus |
| 676 | // WorkerTask() may be called when there's no available work. |
| 677 | return GlobalQueueSize() + worker_count; |
| 678 | } |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 679 | |
Gabriel Charette | 1138d60 | 2020-01-29 08:51:52 | [diff] [blame] | 680 | base::PostJob(FROM_HERE, {}, |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 681 | base::BindRepeating(&WorkerTask), |
| 682 | base::BindRepeating(&NumIncompleteWorkItems)); |
| 683 | ``` |
| 684 | |
| 685 | By doing as much work as possible in a loop when invoked, the worker task avoids |
| 686 | scheduling overhead. Meanwhile `base::JobDelegate::ShouldYield()` is |
| 687 | periodically invoked to conditionally exit and let the scheduler prioritize |
| 688 | other work. This yield-semantic allows, for example, a user-visible job to use |
| 689 | all cores but get out of the way when a user-blocking task comes in. |
| 690 | |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 691 | ### Adding additional work to a running job |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 692 | |
| 693 | When new work items are added and the API user wants additional threads to |
Albert J. Wong | f06ff500 | 2021-07-08 20:37:00 | [diff] [blame] | 694 | invoke the worker task in parallel, |
Etienne Pierre-doray | d388299 | 2020-01-14 20:34:11 | [diff] [blame] | 695 | `JobHandle/JobDelegate::NotifyConcurrencyIncrease()` *must* be invoked shortly |
| 696 | after max concurrency increases. |
| 697 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 698 | ## Testing |
| 699 | |
Gabriel Charette | 0b20ee6 | 2019-09-18 14:06:12 | [diff] [blame] | 700 | For more details see [Testing Components Which Post |
| 701 | Tasks](threading_and_tasks_testing.md). |
| 702 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 703 | To test code that uses `base::ThreadTaskRunnerHandle`, |
| 704 | `base::SequencedTaskRunnerHandle` or a function in |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 705 | [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h), |
| 706 | instantiate a |
Gabriel Charette | 0b20ee6 | 2019-09-18 14:06:12 | [diff] [blame] | 707 | [`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] | 708 | for the scope of the test. If you need BrowserThreads, use |
Gabriel Charette | 798fde7 | 2019-08-20 22:24:04 | [diff] [blame] | 709 | `content::BrowserTaskEnvironment` instead of |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 710 | `base::test::TaskEnvironment`. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 711 | |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 712 | Tests can run the `base::test::TaskEnvironment`'s message pump using a |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 713 | `base::RunLoop`, which can be made to run until `Quit()` (explicitly or via |
| 714 | `RunLoop::QuitClosure()`), or to `RunUntilIdle()` ready-to-run tasks and |
| 715 | immediately return. |
Wez | d9e4cb77 | 2019-01-09 03:07:03 | [diff] [blame] | 716 | |
Wez | 9d5dd28 | 2020-02-10 17:21:22 | [diff] [blame] | 717 | TaskEnvironment configures RunLoop::Run() to GTEST_FAIL() if it hasn't been |
Wez | d9e4cb77 | 2019-01-09 03:07:03 | [diff] [blame] | 718 | explicitly quit after TestTimeouts::action_timeout(). This is preferable to |
| 719 | having the test hang if the code under test fails to trigger the RunLoop to |
Wez | 9d5dd28 | 2020-02-10 17:21:22 | [diff] [blame] | 720 | quit. The timeout can be overridden with base::test::ScopedRunLoopTimeout. |
Wez | d9e4cb77 | 2019-01-09 03:07:03 | [diff] [blame] | 721 | |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 722 | ```cpp |
| 723 | class MyTest : public testing::Test { |
| 724 | public: |
| 725 | // ... |
| 726 | protected: |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 727 | base::test::TaskEnvironment task_environment_; |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 728 | }; |
| 729 | |
| 730 | TEST(MyTest, MyTest) { |
| 731 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&A)); |
| 732 | base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, |
| 733 | base::BindOnce(&B)); |
| 734 | base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( |
| 735 | FROM_HERE, base::BindOnce(&C), base::TimeDelta::Max()); |
| 736 | |
| 737 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until it is empty. |
| 738 | // Delayed tasks are not added to the queue until they are ripe for execution. |
Gabriel Charette | bd126bc3 | 2022-02-01 18:19:19 | [diff] [blame] | 739 | // Prefer explicit exit conditions to RunUntilIdle when possible: |
| 740 | // bit.ly/run-until-idle-with-care2. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 741 | base::RunLoop().RunUntilIdle(); |
| 742 | // A and B have been executed. C is not ripe for execution yet. |
| 743 | |
| 744 | base::RunLoop run_loop; |
| 745 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&D)); |
| 746 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); |
| 747 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&E)); |
| 748 | |
| 749 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until QuitClosure is |
| 750 | // invoked. |
| 751 | run_loop.Run(); |
| 752 | // D and run_loop.QuitClosure() have been executed. E is still in the queue. |
| 753 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 754 | // Tasks posted to thread pool run asynchronously as they are posted. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 755 | base::ThreadPool::PostTask(FROM_HERE, {}, base::BindOnce(&F)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 756 | auto task_runner = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 757 | base::ThreadPool::CreateSequencedTaskRunner({}); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 758 | task_runner->PostTask(FROM_HERE, base::BindOnce(&G)); |
| 759 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 760 | // To block until all tasks posted to thread pool are done running: |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 761 | base::ThreadPoolInstance::Get()->FlushForTesting(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 762 | // F and G have been executed. |
| 763 | |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 764 | base::ThreadPool::PostTaskAndReplyWithResult( |
| 765 | FROM_HERE, {}, base::BindOnce(&H), base::BindOnce(&I)); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 766 | |
| 767 | // This runs the (Thread|Sequenced)TaskRunnerHandle queue until both the |
Gabriel Charette | bd126bc3 | 2022-02-01 18:19:19 | [diff] [blame] | 768 | // (Thread|Sequenced)TaskRunnerHandle queue and the ThreadPool queue are |
| 769 | // empty. Prefer explicit exit conditions to RunUntilIdle when possible: |
| 770 | // bit.ly/run-until-idle-with-care2. |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 771 | task_environment_.RunUntilIdle(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 772 | // E, H, I have been executed. |
| 773 | } |
| 774 | ``` |
| 775 | |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 776 | ## Using ThreadPool in a New Process |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 777 | |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 778 | ThreadPoolInstance needs to be initialized in a process before the functions in |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 779 | [`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] | 780 | can be used. Initialization of ThreadPoolInstance in the Chrome browser process |
| 781 | and child processes (renderer, GPU, utility) has already been taken care of. To |
| 782 | use ThreadPoolInstance in another process, initialize ThreadPoolInstance early |
| 783 | in the main function: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 784 | |
| 785 | ```cpp |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 786 | // This initializes and starts ThreadPoolInstance with default params. |
| 787 | base::ThreadPoolInstance::CreateAndStartWithDefaultParams(“process_name”); |
| 788 | // The base/task/post_task.h API can now be used with base::ThreadPool trait. |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 789 | // Tasks will be scheduled as they are posted. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 790 | |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 791 | // This initializes ThreadPoolInstance. |
| 792 | base::ThreadPoolInstance::Create(“process_name”); |
| 793 | // The base/task/post_task.h API can now be used with base::ThreadPool trait. No |
| 794 | // threads will be created and no tasks will be scheduled until after Start() is |
| 795 | // called. |
| 796 | base::ThreadPoolInstance::Get()->Start(params); |
Gabriel Charette | 52fa3ae | 2019-04-15 21:44:37 | [diff] [blame] | 797 | // ThreadPool can now create threads and schedule tasks. |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 798 | ``` |
| 799 | |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 800 | And shutdown ThreadPoolInstance late in the main function: |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 801 | |
| 802 | ```cpp |
Gabriel Charette | 43fd370 | 2019-05-29 16:36:51 | [diff] [blame] | 803 | base::ThreadPoolInstance::Get()->Shutdown(); |
fdoray | bacba4a2 | 2017-05-10 21:10:00 | [diff] [blame] | 804 | // Tasks posted with TaskShutdownBehavior::BLOCK_SHUTDOWN and |
| 805 | // tasks posted with TaskShutdownBehavior::SKIP_ON_SHUTDOWN that |
| 806 | // have started to run before the Shutdown() call have now completed their |
| 807 | // execution. Tasks posted with |
| 808 | // TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN may still be |
| 809 | // running. |
| 810 | ``` |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 811 | ## TaskRunner ownership (encourage no dependency injection) |
Sebastien Marchand | c95489b | 2017-05-25 16:39:34 | [diff] [blame] | 812 | |
| 813 | TaskRunners shouldn't be passed through several components. Instead, the |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 814 | component that uses a TaskRunner should be the one that creates it. |
Sebastien Marchand | c95489b | 2017-05-25 16:39:34 | [diff] [blame] | 815 | |
| 816 | See [this example](https://codereview.chromium.org/2885173002/) of a |
| 817 | refactoring where a TaskRunner was passed through a lot of components only to be |
| 818 | used in an eventual leaf. The leaf can and should now obtain its TaskRunner |
| 819 | directly from |
Gabriel Charette | 04b138f | 2018-08-06 00:03:22 | [diff] [blame] | 820 | [`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] | 821 | |
Gabriel Charette | 694c3c33 | 2019-08-19 14:53:05 | [diff] [blame] | 822 | As mentioned above, `base::test::TaskEnvironment` allows unit tests to |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 823 | control tasks posted from underlying TaskRunners. In rare cases where a test |
| 824 | needs to more precisely control task ordering: dependency injection of |
| 825 | TaskRunners can be useful. For such cases the preferred approach is the |
| 826 | following: |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 827 | |
| 828 | ```cpp |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 829 | class Foo { |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 830 | public: |
| 831 | |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 832 | // Overrides |background_task_runner_| in tests. |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 833 | void SetBackgroundTaskRunnerForTesting( |
Gabriel Charette | 39db4c6 | 2019-04-29 19:52:38 | [diff] [blame] | 834 | scoped_refptr<base::SequencedTaskRunner> background_task_runner) { |
| 835 | background_task_runner_ = std::move(background_task_runner); |
| 836 | } |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 837 | |
| 838 | private: |
michaelpg | 12c0457 | 2017-06-26 23:25:06 | [diff] [blame] | 839 | scoped_refptr<base::SequencedTaskRunner> background_task_runner_ = |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 840 | base::ThreadPool::CreateSequencedTaskRunner( |
Gabriel Charette | b10aeeb | 2018-07-26 20:15:00 | [diff] [blame] | 841 | {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); |
Gabriel Charette | b86e5fe6 | 2017-06-08 19:39:28 | [diff] [blame] | 842 | } |
| 843 | ``` |
| 844 | |
| 845 | Note that this still allows removing all layers of plumbing between //chrome and |
| 846 | that component since unit tests will use the leaf layer directly. |
Gabriel Charette | 8917f4c | 2018-11-22 15:50:28 | [diff] [blame] | 847 | |
| 848 | ## FAQ |
| 849 | See [Threading and Tasks FAQ](threading_and_tasks_faq.md) for more examples. |
Gabriel Charette | 43de5c4 | 2020-01-27 22:44:45 | [diff] [blame] | 850 | |
| 851 | [task APIs v3]: https://docs.google.com/document/d/1tssusPykvx3g0gvbvU4HxGyn3MjJlIylnsH13-Tv6s4/edit?ts=5de99a52#heading=h.ss4tw38hvh3s |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 852 | |
| 853 | ## Internals |
| 854 | |
| 855 | ### SequenceManager |
| 856 | |
| 857 | [SequenceManager](https://cs.chromium.org/chromium/src/base/task/sequence_manager/sequence_manager.h) |
| 858 | manages TaskQueues which have different properties (e.g. priority, common task |
| 859 | type) multiplexing all posted tasks into a single backing sequence. This will |
| 860 | usually be a MessagePump. Depending on the type of message pump used other |
| 861 | events such as UI messages may be processed as well. On Windows APC calls (as |
| 862 | time permits) and signals sent to a registered set of HANDLEs may also be |
| 863 | processed. |
| 864 | |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 865 | ### MessagePump |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 866 | |
| 867 | [MessagePumps](https://cs.chromium.org/chromium/src/base/message_loop/message_pump.h) |
| 868 | are responsible for processing native messages as well as for giving cycles to |
| 869 | their delegate (SequenceManager) periodically. MessagePumps take care to mixing |
| 870 | delegate callbacks with native message processing so neither type of event |
| 871 | starves the other of cycles. |
| 872 | |
| 873 | There are different [MessagePumpTypes](https://cs.chromium.org/chromium/src/base/message_loop/message_pump_type.h), |
| 874 | most common are: |
| 875 | |
| 876 | * DEFAULT: Supports tasks and timers only |
| 877 | |
| 878 | * UI: Supports native UI events (e.g. Windows messages) |
| 879 | |
| 880 | * IO: Supports asynchronous IO (not file I/O!) |
| 881 | |
| 882 | * CUSTOM: User provided implementation of MessagePump interface |
| 883 | |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 884 | ### RunLoop |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 885 | |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 886 | RunLoop is a helper class to run the RunLoop::Delegate associated with the |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 887 | current thread (usually a SequenceManager). Create a RunLoop on the stack and |
| 888 | call Run/Quit to run a nested RunLoop but please avoid nested loops in |
| 889 | production code! |
| 890 | |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 891 | ### Task Reentrancy |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 892 | |
| 893 | SequenceManager has task reentrancy protection. This means that if a |
| 894 | task is being processed, a second task cannot start until the first task is |
| 895 | finished. Reentrancy can happen when processing a task, and an inner |
| 896 | message pump is created. That inner pump then processes native messages |
| 897 | which could implicitly start an inner task. Inner message pumps are created |
| 898 | with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions |
| 899 | (DoDragDrop), printer functions (StartDoc) and *many* others. |
| 900 | |
| 901 | ```cpp |
| 902 | Sample workaround when inner task processing is needed: |
| 903 | HRESULT hr; |
| 904 | { |
Carlos Caballero | b25fe847 | 2020-07-17 10:27:17 | [diff] [blame] | 905 | CurrentThread::ScopedNestableTaskAllower allow; |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 906 | hr = DoDragDrop(...); // Implicitly runs a modal message loop. |
| 907 | } |
| 908 | // Process |hr| (the result returned by DoDragDrop()). |
| 909 | ``` |
| 910 | |
| 911 | Please be SURE your task is reentrant (nestable) and all global variables |
| 912 | are stable and accessible before before using |
Carlos Caballero | b25fe847 | 2020-07-17 10:27:17 | [diff] [blame] | 913 | CurrentThread::ScopedNestableTaskAllower. |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 914 | |
| 915 | ## APIs for general use |
| 916 | |
| 917 | User code should hardly ever need to access SequenceManager APIs directly as |
| 918 | these are meant for code that deals with scheduling. Instead you should use the |
| 919 | following: |
| 920 | |
| 921 | * base::RunLoop: Drive the SequenceManager from the thread it's bound to. |
| 922 | |
| 923 | * base::Thread/SequencedTaskRunnerHandle: Post back to the SequenceManager TaskQueues from a task running on it. |
| 924 | |
| 925 | * SequenceLocalStorageSlot : Bind external state to a sequence. |
| 926 | |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 927 | * base::CurrentThread : Proxy to a subset of Task related APIs bound to the current thread |
Carlos Caballero | 40b6d04 | 2020-06-16 06:50:25 | [diff] [blame] | 928 | |
| 929 | * Embedders may provide their own static accessors to post tasks on specific loops (e.g. content::BrowserThreads). |
| 930 | |
| 931 | ### SingleThreadTaskExecutor and TaskEnvironment |
| 932 | |
| 933 | Instead of having to deal with SequenceManager and TaskQueues code that needs a |
| 934 | simple task posting environment (one default task queue) can use a |
| 935 | [SingleThreadTaskExecutor](https://cs.chromium.org/chromium/src/base/task/single_thread_task_executor.h). |
| 936 | |
| 937 | Unit tests can use [TaskEnvironment](https://cs.chromium.org/chromium/src/base/test/task_environment.h) |
| 938 | which is highly configurable. |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 939 | |
Wen Fan | e09439ca | 2021-03-09 16:50:41 | [diff] [blame] | 940 | ## MessageLoop and MessageLoopCurrent |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 941 | |
Wen Fan | e09439ca | 2021-03-09 16:50:41 | [diff] [blame] | 942 | You might come across references to MessageLoop or MessageLoopCurrent in the |
Carlos Caballero | 4a05092 | 2020-07-02 11:43:38 | [diff] [blame] | 943 | code or documentation. These classes no longer exist and we are in the process |
Jared Saul | ea867ab | 2021-07-15 17:39:01 | [diff] [blame] | 944 | or getting rid of all references to them. `base::MessageLoopCurrent` was |
| 945 | replaced by `base::CurrentThread` and the drop in replacements for |
| 946 | `base::MessageLoop` are `base::SingleThreadTaskExecutor` and |
| 947 | `base::Test::TaskEnvironment`. |