blob: 4d20df17217884e9b99daa2ec74dab0df27458cd [file] [log] [blame] [view]
fdoraybacba4a22017-05-10 21:10:001# Threading and Tasks in Chrome
2
3[TOC]
4
Gabriel Charette8917f4c2018-11-22 15:50:285Note: See [Threading and Tasks FAQ](threading_and_tasks_faq.md) for more
6examples.
7
fdoraybacba4a22017-05-10 21:10:008## Overview
9
Gabriel Charette39db4c62019-04-29 19:52:3810Chrome has a [multi-process
11architecture](https://www.chromium.org/developers/design-documents/multi-process-architecture)
12and each process is heavily multi-threaded. In this document we will go over the
13basic threading system shared by each process. The main goal is to keep the main
14thread (a.k.a. "UI" thread in the browser process) and IO thread (each process'
15thread for handling
16[IPC](https://en.wikipedia.org/wiki/Inter-process_communication)) responsive.
17This means offloading any blocking I/O or other expensive operations to other
18threads. Our approach is to use message passing as the way of communicating
19between threads. We discourage locking and thread-safe objects. Instead, objects
20live on only one (often virtual -- we'll get to that later!) thread and we pass
21messages between those threads for communication.
22
23This documentation assumes familiarity with computer science
24[threading concepts](https://en.wikipedia.org/wiki/Thread_(computing)).
Gabriel Charette90480312018-02-16 15:10:0525
Gabriel Charette364a16a2019-02-06 21:12:1526### Nomenclature
Gabriel Charette39db4c62019-04-29 19:52:3827
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 Charette0b20ee62019-09-18 14:06:1241 Chrome, this is `base::ThreadPoolInstance`. There's exactly one instance per
42 Chrome process, it serves tasks posted through
Gabriel Charette39db4c62019-04-29 19:52:3843 [`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h)
Gabriel Charette43fd3702019-05-29 16:36:5144 and as such you should rarely need to use the `base::ThreadPoolInstance` API
Gabriel Charette39db4c62019-04-29 19:52:3845 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
66Note to the reader: the following terms are an attempt to bridge the gap between
67common threading nomenclature and the way we use them in Chrome. It might be a
68bit heavy if you're just getting started. Should this be hard to parse, consider
69skipping to the more detailed sections below and referring back to this as
70necessary.
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 Charette364a16a2019-02-06 21:12:1579 * **Thread-affine**: Such types/methods need to be always accessed from the
Gabriel Charetteb984d672019-02-12 21:53:2780 same physical thread (i.e. from the same `base::SingleThreadTaskRunner`) and
Gabriel Charette39db4c62019-04-29 19:52:3881 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 Charetteb984d672019-02-12 21:53:2785 thread-affine is a subset of thread-unsafe. Thread-affine is also sometimes
86 referred to as **thread-hostile**.
Gabriel Charette364a16a2019-02-06 21:12:1587 * **Thread-safe**: Such types/methods can be safely accessed concurrently.
Gabriel Charetteb984d672019-02-12 21:53:2788 * **Thread-compatible**: Such types provide safe concurrent access to const
89 methods but require synchronization for non-const (or mixed const/non-const
Gabriel Charette39db4c62019-04-29 19:52:3890 access). Chrome doesn't expose reader-writer locks; as such, the only use
Gabriel Charetteb984d672019-02-12 21:53:2791 case for this is objects (typically globals) which are initialized once in a
Gabriel Charette364a16a2019-02-06 21:12:1592 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 Charetteb984d672019-02-12 21:53:2794 `base::NoDestructor`) and forever after immutable.
95 * **Immutable**: A subset of thread-compatible types which cannot be modified
96 after construction.
Gabriel Charette364a16a2019-02-06 21:12:1597 * **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 Charette39db4c62019-04-29 19:52:38101 scenarios. See [Prefer Sequences to
102 Threads](#prefer-sequences-to-physical-threads) below for more details.
Gabriel Charette364a16a2019-02-06 21:12:15103
fdoraybacba4a22017-05-10 21:10:00104### Threads
105
106Every Chrome process has
107
108* a main thread
Gabriel Charette39db4c62019-04-29 19:52:38109 * in the browser process (BrowserThread::UI): updates the UI
110 * in renderer processes (Blink main thread): runs most of Blink
fdoraybacba4a22017-05-10 21:10:00111* an IO thread
Gabriel Charette39db4c62019-04-29 19:52:38112 * in the browser process (BrowserThread::IO): handles IPCs and network requests
fdoraybacba4a22017-05-10 21:10:00113 * in renderer processes: handles IPCs
114* a few more special-purpose threads
115* and a pool of general-purpose threads
116
117Most threads have a loop that gets tasks from a queue and runs them (the queue
118may be shared between multiple threads).
119
120### Tasks
121
122A task is a `base::OnceClosure` added to a queue for asynchronous execution.
123
124A `base::OnceClosure` stores a function pointer and arguments. It has a `Run()`
125method that invokes the function pointer using the bound arguments. It is
126created using `base::BindOnce`. (ref. [Callback<> and Bind()
127documentation](callback.md)).
128
129```
130void TaskA() {}
131void TaskB(int v) {}
132
133auto task_a = base::BindOnce(&TaskA);
134auto task_b = base::BindOnce(&TaskB, 42);
135```
136
137A 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 Stonebraker653a3ba2019-07-02 19:24:23145 * [COM Single Threaded](#Posting-Tasks-to-a-COM-Single_Thread-Apartment-STA_Thread-Windows):
fdoraybacba4a22017-05-10 21:10:00146 A variant of single threaded with COM initialized.
147
Gabriel Charette39db4c62019-04-29 19:52:38148### Prefer Sequences to Physical Threads
gab2a4576052017-06-07 23:36:12149
Gabriel Charette39db4c62019-04-29 19:52:38150Sequenced execution (on virtual threads) is strongly preferred to
151single-threaded execution (on physical threads). Except for types/methods bound
152to 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).
gab2a4576052017-06-07 23:36:12155
Gabriel Charette39db4c62019-04-29 19:52:38156All 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)).
gab2a4576052017-06-07 23:36:12159
Gabriel Charette39db4c62019-04-29 19:52:38160If you find yourself writing a sequence-friendly type and it fails
161thread-affinity checks (e.g., `THREAD_CHECKER`) in a leaf dependency: consider
162making that dependency sequence-friendly as well. Most core APIs in Chrome are
163sequence-friendly, but some legacy types may still over-zealously use
164ThreadChecker/ThreadTaskRunnerHandle/SingleThreadTaskRunner when they could
165instead rely on the "current sequence" and no longer be thread-affine.
fdoraybacba4a22017-05-10 21:10:00166
167## Posting a Parallel Task
168
Gabriel Charette52fa3ae2019-04-15 21:44:37169### Direct Posting to the Thread Pool
fdoraybacba4a22017-05-10 21:10:00170
171A task that can run on any thread and doesn’t have ordering or mutual exclusion
172requirements with other tasks should be posted using one of the
173`base::PostTask*()` functions defined in
Gabriel Charette04b138f2018-08-06 00:03:22174[`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h).
fdoraybacba4a22017-05-10 21:10:00175
176```cpp
177base::PostTask(FROM_HERE, base::BindOnce(&Task));
178```
179
180This posts tasks with default traits.
181
Sami Kyostila831c60b2019-07-31 13:31:23182The `base::PostTask*()` functions allow the caller to provide additional details
183about the task via TaskTraits (ref. [Annotating Tasks with TaskTraits](#Annotating-Tasks-with-TaskTraits)).
fdoraybacba4a22017-05-10 21:10:00184
185```cpp
Sami Kyostila831c60b2019-07-31 13:31:23186base::PostTask(
Gabriel Charetteb10aeeb2018-07-26 20:15:00187 FROM_HERE, {base::TaskPriority::BEST_EFFORT, MayBlock()},
fdoraybacba4a22017-05-10 21:10:00188 base::BindOnce(&Task));
189```
190
fdoray52bf5552017-05-11 12:43:59191### Posting via a TaskRunner
fdoraybacba4a22017-05-10 21:10:00192
193A parallel
Gabriel Charette39db4c62019-04-29 19:52:38194[`base::TaskRunner`](https://cs.chromium.org/chromium/src/base/task_runner.h) is
195an alternative to calling `base::PostTask*()` directly. This is mainly useful
196when it isn’t known in advance whether tasks will be posted in parallel, in
197sequence, or to a single-thread (ref. [Posting a Sequenced
198Task](#Posting-a-Sequenced-Task), [Posting Multiple Tasks to the Same
199Thread](#Posting-Multiple-Tasks-to-the-Same-Thread)). Since `base::TaskRunner`
200is the base class of `base::SequencedTaskRunner` and
201`base::SingleThreadTaskRunner`, a `scoped_refptr<TaskRunner>` member can hold a
202`base::TaskRunner`, a `base::SequencedTaskRunner` or a
203`base::SingleThreadTaskRunner`.
fdoraybacba4a22017-05-10 21:10:00204
205```cpp
206class A {
207 public:
208 A() = default;
209
fdoraybacba4a22017-05-10 21:10:00210 void DoSomething() {
fdoraybacba4a22017-05-10 21:10:00211 task_runner_->PostTask(FROM_HERE, base::BindOnce(&A));
212 }
213
214 private:
215 scoped_refptr<base::TaskRunner> task_runner_ =
Sami Kyostila831c60b2019-07-31 13:31:23216 base::CreateTaskRunner({base::TaskPriority::USER_VISIBLE});
fdoraybacba4a22017-05-10 21:10:00217};
218```
219
220Unless a test needs to control precisely how tasks are executed, it is preferred
221to call `base::PostTask*()` directly (ref. [Testing](#Testing) for less invasive
222ways of controlling tasks in tests).
223
224## Posting a Sequenced Task
225
226A sequence is a set of tasks that run one at a time in posting order (not
227necessarily on the same thread). To post tasks as part of a sequence, use a
Gabriel Charette39db4c62019-04-29 19:52:38228[`base::SequencedTaskRunner`](https://cs.chromium.org/chromium/src/base/sequenced_task_runner.h).
fdoraybacba4a22017-05-10 21:10:00229
230### Posting to a New Sequence
231
Gabriel Charette39db4c62019-04-29 19:52:38232A `base::SequencedTaskRunner` can be created by
Sami Kyostila831c60b2019-07-31 13:31:23233`base::CreateSequencedTaskRunner()`.
fdoraybacba4a22017-05-10 21:10:00234
235```cpp
236scoped_refptr<SequencedTaskRunner> sequenced_task_runner =
Sami Kyostila831c60b2019-07-31 13:31:23237 base::CreateSequencedTaskRunner(...);
fdoraybacba4a22017-05-10 21:10:00238
239// TaskB runs after TaskA completes.
240sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA));
241sequenced_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB));
242```
243
Alex Clarke0dd499562019-10-18 19:45:09244### Posting to the Current (Virtual) Thread
245
246The preferred way of posting to the current thread is via the
247`base::CurrentThread` trait.
248
249```cpp
250// The task will run on the current (virtual) thread's default task queue.
251base::PostTask(FROM_HERE, {base::CurrentThread()}, base::BindOnce(&Task));
252```
253
254You can optionally specify additional traits. This is important because some
255threads such as the Browser UI thread, Browser IO thread and the Blink main
256thread have multiple task queues funneled onto the same thread and the default
257priority may not be suitable your task.
258
259E.g. you can explicitly set the priority:
260
261```cpp
262// The task will run on the current (virtual) thread's best effort queue.
263// NOTE only the Browser UI and Browser IO threads support task priority (for
264// now), other (virtual) threads will silently ignore traits used in combination
265// with `base::CurrentThread`.
266base::PostTask(FROM_HERE,
267 {base::CurrentThread(), base::TaskPriority::BEST_EFFORT},
268 base::BindOnce(&Task));
269```
fdoraybacba4a22017-05-10 21:10:00270
Gabriel Charette39db4c62019-04-29 19:52:38271The `base::SequencedTaskRunner` to which the current task was posted can be
272obtained via
Alex Clarke0dd499562019-10-18 19:45:09273[`base::GetContinuationTaskRunner()`](https://cs.chromium.org/chromium/src/base/task/post_task.h).
274
275On some threads there is only one task runner so the current sequence is the
276same as the current thread. That's not the case in the Browser UI, Browser IO or
277Blink main threads. Additionally the notion of the current sequence doesn't
278exist for parallel threadpool tasks or when there's no task running, and
279`base::GetContinuationTaskRunner()` will DCHECK in those circumstances.
fdoraybacba4a22017-05-10 21:10:00280
281*** note
Alex Clarke0dd499562019-10-18 19:45:09282**NOTE:** While its invalid to call `base::GetContinuationTaskRunner()` from a
283parallel task, it is valid from a sequenced or a single-threaded task. I.e. from
284a `base::SequencedTaskRunner` or a `base::SingleThreadTaskRunner`.
fdoraybacba4a22017-05-10 21:10:00285***
286
287```cpp
288// The task will run after any task that has already been posted
289// to the SequencedTaskRunner to which the current task was posted
290// (in particular, it will run after the current task completes).
291// It is also guaranteed that it won’t run concurrently with any
292// task posted to that SequencedTaskRunner.
Alex Clarke0dd499562019-10-18 19:45:09293base::GetContinuationTaskRunner()->
fdoraybacba4a22017-05-10 21:10:00294 PostTask(FROM_HERE, base::BindOnce(&Task));
295```
296
Alex Clarke0dd499562019-10-18 19:45:09297You can also obtain the current thread's default task runner via the
298`base::CurrentThread` trait, however you can specify additional traits. This is
299important because some threads such as the Browser UI thread and the Blink main
300thread have multiple task queues funneled onto the same thread and the default
301priority may not suit your task. E.g. you can explicitly set the priority:
302
303```cpp
304// The task will run on the current (virtual) thread's best effort queue.
305// NOTE only the Browser UI and Browser IO threads support task priority, other
306// (virtual) threads will silently ignore traits used in combination with
307// `base::CurrentThread`.
308base::PostTask(FROM_HERE,
309 {base::CurrentThread(), base::TaskPriority::BEST_EFFORT},
310 base::BindOnce(&Task));
311```
312
313If you need to obtain a task runner with these traits you can do so via
314 `base::CreateSequencedTaskRunner()`.
315
316```cpp
317// Tasks posted to |task_runner| will run on the current (virtual) thread's best
318// effort queue.
319auto task_runner = base::CreateSequencedTaskRunner(
320 {base::CurrentThread(), base::TaskPriority::BEST_EFFORT});
321```
322
323
fdoraybacba4a22017-05-10 21:10:00324## Using Sequences Instead of Locks
325
326Usage of locks is discouraged in Chrome. Sequences inherently provide
Gabriel Charettea3ccc972018-11-13 14:43:12327thread-safety. Prefer classes that are always accessed from the same
328sequence to managing your own thread-safety with locks.
329
330**Thread-safe but not thread-affine; how so?** Tasks posted to the same sequence
331will run in sequential order. After a sequenced task completes, the next task
332may be picked up by a different worker thread, but that task is guaranteed to
333see any side-effects caused by the previous one(s) on its sequence.
fdoraybacba4a22017-05-10 21:10:00334
335```cpp
336class A {
337 public:
338 A() {
339 // Do not require accesses to be on the creation sequence.
isherman8c33b8a2017-06-27 19:18:30340 DETACH_FROM_SEQUENCE(sequence_checker_);
fdoraybacba4a22017-05-10 21:10:00341 }
342
343 void AddValue(int v) {
344 // Check that all accesses are on the same sequence.
isherman8c33b8a2017-06-27 19:18:30345 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
fdoraybacba4a22017-05-10 21:10:00346 values_.push_back(v);
347}
348
349 private:
isherman8c33b8a2017-06-27 19:18:30350 SEQUENCE_CHECKER(sequence_checker_);
fdoraybacba4a22017-05-10 21:10:00351
352 // No lock required, because all accesses are on the
353 // same sequence.
354 std::vector<int> values_;
355};
356
357A a;
358scoped_refptr<SequencedTaskRunner> task_runner_for_a = ...;
Mike Bjorged3a09842018-05-15 18:37:28359task_runner_for_a->PostTask(FROM_HERE,
360 base::BindOnce(&A::AddValue, base::Unretained(&a), 42));
361task_runner_for_a->PostTask(FROM_HERE,
362 base::BindOnce(&A::AddValue, base::Unretained(&a), 27));
fdoraybacba4a22017-05-10 21:10:00363
364// Access from a different sequence causes a DCHECK failure.
365scoped_refptr<SequencedTaskRunner> other_task_runner = ...;
366other_task_runner->PostTask(FROM_HERE,
Mike Bjorged3a09842018-05-15 18:37:28367 base::BindOnce(&A::AddValue, base::Unretained(&a), 1));
fdoraybacba4a22017-05-10 21:10:00368```
369
Gabriel Charette90480312018-02-16 15:10:05370Locks should only be used to swap in a shared data structure that can be
371accessed on multiple threads. If one thread updates it based on expensive
372computation or through disk access, then that slow work should be done without
Gabriel Charette39db4c62019-04-29 19:52:38373holding the lock. Only when the result is available should the lock be used to
374swap in the new data. An example of this is in PluginList::LoadPlugins
375([`content/browser/plugin_list.cc`](https://cs.chromium.org/chromium/src/content/browser/plugin_list.cc).
376If you must use locks,
Gabriel Charette90480312018-02-16 15:10:05377[here](https://www.chromium.org/developers/lock-and-condition-variable) are some
378best practices and pitfalls to avoid.
379
Gabriel Charette39db4c62019-04-29 19:52:38380In order to write non-blocking code, many APIs in Chrome are asynchronous.
Gabriel Charette90480312018-02-16 15:10:05381Usually this means that they either need to be executed on a particular
382thread/sequence and will return results via a custom delegate interface, or they
383take a `base::Callback<>` object that is called when the requested operation is
384completed. Executing work on a specific thread/sequence is covered in the
385PostTask sections above.
386
fdoraybacba4a22017-05-10 21:10:00387## Posting Multiple Tasks to the Same Thread
388
389If multiple tasks need to run on the same thread, post them to a
Gabriel Charette39db4c62019-04-29 19:52:38390[`base::SingleThreadTaskRunner`](https://cs.chromium.org/chromium/src/base/single_thread_task_runner.h).
391All tasks posted to the same `base::SingleThreadTaskRunner` run on the same thread in
fdoraybacba4a22017-05-10 21:10:00392posting order.
393
394### Posting to the Main Thread or to the IO Thread in the Browser Process
395
Eric Seckler6cf08db82018-08-30 12:01:55396To post tasks to the main thread or to the IO thread, use
Sami Kyostila831c60b2019-07-31 13:31:23397`base::PostTask()` or get the appropriate SingleThreadTaskRunner using
398`base::CreateSingleThreadTaskRunner`, supplying a `BrowserThread::ID`
Eric Seckler6cf08db82018-08-30 12:01:55399as trait. For this, you'll also need to include
400[`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h).
fdoraybacba4a22017-05-10 21:10:00401
402```cpp
Sami Kyostila831c60b2019-07-31 13:31:23403base::PostTask(FROM_HERE, {content::BrowserThread::UI}, ...);
fdoraybacba4a22017-05-10 21:10:00404
Sami Kyostila831c60b2019-07-31 13:31:23405base::CreateSingleThreadTaskRunner({content::BrowserThread::IO})
fdoraybacba4a22017-05-10 21:10:00406 ->PostTask(FROM_HERE, ...);
407```
408
409The main thread and the IO thread are already super busy. Therefore, prefer
fdoray52bf5552017-05-11 12:43:59410posting to a general purpose thread when possible (ref.
411[Posting a Parallel Task](#Posting-a-Parallel-Task),
412[Posting a Sequenced task](#Posting-a-Sequenced-Task)).
413Good reasons to post to the main thread are to update the UI or access objects
414that are bound to it (e.g. `Profile`). A good reason to post to the IO thread is
415to access the internals of components that are bound to it (e.g. IPCs, network).
416Note: It is not necessary to have an explicit post task to the IO thread to
417send/receive an IPC or send/receive data on the network.
fdoraybacba4a22017-05-10 21:10:00418
419### Posting to the Main Thread in a Renderer Process
420TODO
421
422### Posting to a Custom SingleThreadTaskRunner
423
424If multiple tasks need to run on the same thread and that thread doesn’t have to
Gabriel Charette39db4c62019-04-29 19:52:38425be the main thread or the IO thread, post them to a `base::SingleThreadTaskRunner`
Sami Kyostila831c60b2019-07-31 13:31:23426created by `base::CreateSingleThreadTaskRunner`.
fdoraybacba4a22017-05-10 21:10:00427
428```cpp
Dominic Farolinodbe9769b2019-05-31 04:06:03429scoped_refptr<SingleThreadTaskRunner> single_thread_task_runner =
Sami Kyostila831c60b2019-07-31 13:31:23430 base::CreateSingleThreadTaskRunner(...);
fdoraybacba4a22017-05-10 21:10:00431
432// TaskB runs after TaskA completes. Both tasks run on the same thread.
433single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskA));
434single_thread_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskB));
435```
436
Gabriel Charette39db4c62019-04-29 19:52:38437Remember that we [prefer sequences to physical
438threads](#prefer-sequences-to-physical-threads) and that this thus should rarely
439be necessary.
fdoraybacba4a22017-05-10 21:10:00440
fdoraybacba4a22017-05-10 21:10:00441## Posting Tasks to a COM Single-Thread Apartment (STA) Thread (Windows)
442
443Tasks that need to run on a COM Single-Thread Apartment (STA) thread must be
Gabriel Charette39db4c62019-04-29 19:52:38444posted to a `base::SingleThreadTaskRunner` returned by
Sami Kyostila831c60b2019-07-31 13:31:23445`base::CreateCOMSTATaskRunner()`. As mentioned in [Posting Multiple Tasks to the
446Same Thread](#Posting-Multiple-Tasks-to-the-Same-Thread), all tasks posted to
447the same `base::SingleThreadTaskRunner` run on the same thread in posting order.
fdoraybacba4a22017-05-10 21:10:00448
449```cpp
450// Task(A|B|C)UsingCOMSTA will run on the same COM STA thread.
451
452void TaskAUsingCOMSTA() {
453 // [ This runs on a COM STA thread. ]
454
455 // Make COM STA calls.
456 // ...
457
458 // Post another task to the current COM STA thread.
459 base::ThreadTaskRunnerHandle::Get()->PostTask(
460 FROM_HERE, base::BindOnce(&TaskCUsingCOMSTA));
461}
462void TaskBUsingCOMSTA() { }
463void TaskCUsingCOMSTA() { }
464
Sami Kyostila831c60b2019-07-31 13:31:23465auto com_sta_task_runner = base::CreateCOMSTATaskRunner(...);
fdoraybacba4a22017-05-10 21:10:00466com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskAUsingCOMSTA));
467com_sta_task_runner->PostTask(FROM_HERE, base::BindOnce(&TaskBUsingCOMSTA));
468```
469
470## Annotating Tasks with TaskTraits
471
Gabriel Charette39db4c62019-04-29 19:52:38472[`base::TaskTraits`](https://cs.chromium.org/chromium/src/base/task/task_traits.h)
Gabriel Charette52fa3ae2019-04-15 21:44:37473encapsulate information about a task that helps the thread pool make better
fdoraybacba4a22017-05-10 21:10:00474scheduling decisions.
475
Gabriel Charette39db4c62019-04-29 19:52:38476All `base::PostTask*()` functions in
Gabriel Charette04b138f2018-08-06 00:03:22477[`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h)
Gabriel Charette39db4c62019-04-29 19:52:38478have an overload that takes `base::TaskTraits` as argument and one that doesn’t.
479The overload that doesn’t take `base::TaskTraits` as argument is appropriate for
480tasks that:
fdoraybacba4a22017-05-10 21:10:00481- Don’t block (ref. MayBlock and WithBaseSyncPrimitives).
482- Prefer inheriting the current priority to specifying their own.
Gabriel Charette52fa3ae2019-04-15 21:44:37483- Can either block shutdown or be skipped on shutdown (thread pool is free to
484 choose a fitting default).
fdoraybacba4a22017-05-10 21:10:00485Tasks that don’t match this description must be posted with explicit TaskTraits.
486
Gabriel Charette04b138f2018-08-06 00:03:22487[`base/task/task_traits.h`](https://cs.chromium.org/chromium/src/base/task/task_traits.h)
Eric Seckler6cf08db82018-08-30 12:01:55488provides exhaustive documentation of available traits. The content layer also
489provides additional traits in
490[`content/public/browser/browser_task_traits.h`](https://cs.chromium.org/chromium/src/content/public/browser/browser_task_traits.h)
491to facilitate posting a task onto a BrowserThread.
492
Gabriel Charette39db4c62019-04-29 19:52:38493Below are some examples of how to specify `base::TaskTraits`.
fdoraybacba4a22017-05-10 21:10:00494
495```cpp
496// This task has no explicit TaskTraits. It cannot block. Its priority
497// is inherited from the calling context (e.g. if it is posted from
Gabriel Charette141a442582018-07-27 21:23:25498// a BEST_EFFORT task, it will have a BEST_EFFORT priority). It will either
fdoraybacba4a22017-05-10 21:10:00499// block shutdown or be skipped on shutdown.
500base::PostTask(FROM_HERE, base::BindOnce(...));
501
Gabriel Charette52fa3ae2019-04-15 21:44:37502// This task has the highest priority. The thread pool will try to
Gabriel Charette141a442582018-07-27 21:23:25503// run it before USER_VISIBLE and BEST_EFFORT tasks.
Sami Kyostila831c60b2019-07-31 13:31:23504base::PostTask(
fdoraybacba4a22017-05-10 21:10:00505 FROM_HERE, {base::TaskPriority::USER_BLOCKING},
506 base::BindOnce(...));
507
508// This task has the lowest priority and is allowed to block (e.g. it
509// can read a file from disk).
Sami Kyostila831c60b2019-07-31 13:31:23510base::PostTask(
Gabriel Charetteb10aeeb2018-07-26 20:15:00511 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
fdoraybacba4a22017-05-10 21:10:00512 base::BindOnce(...));
513
514// This task blocks shutdown. The process won't exit before its
515// execution is complete.
Sami Kyostila831c60b2019-07-31 13:31:23516base::PostTask(
fdoraybacba4a22017-05-10 21:10:00517 FROM_HERE, {base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
518 base::BindOnce(...));
Eric Seckler6cf08db82018-08-30 12:01:55519
520// This task will run on the Browser UI thread.
Sami Kyostila831c60b2019-07-31 13:31:23521base::PostTask(
Eric Seckler6cf08db82018-08-30 12:01:55522 FROM_HERE, {content::BrowserThread::UI},
523 base::BindOnce(...));
Alex Clarke0dd499562019-10-18 19:45:09524
525// This task will run on the current virtual thread (sequence).
526base::PostTask(
527 FROM_HERE, {base::CurrentThread()},
528 base::BindOnce(...));
529
530// This task will run on the current virtual thread (sequence) with best effort
531// priority.
532base::PostTask(
533 FROM_HERE, {base::CurrentThread(), base::TaskPriority::BEST_EFFORT},
534 base::BindOnce(...));
fdoraybacba4a22017-05-10 21:10:00535```
536
537## Keeping the Browser Responsive
538
539Do not perform expensive work on the main thread, the IO thread or any sequence
540that is expected to run tasks with a low latency. Instead, perform expensive
541work asynchronously using `base::PostTaskAndReply*()` or
Gabriel Charette39db4c62019-04-29 19:52:38542`base::SequencedTaskRunner::PostTaskAndReply()`. Note that
543asynchronous/overlapped I/O on the IO thread are fine.
fdoraybacba4a22017-05-10 21:10:00544
545Example: Running the code below on the main thread will prevent the browser from
546responding to user input for a long time.
547
548```cpp
549// GetHistoryItemsFromDisk() may block for a long time.
550// AddHistoryItemsToOmniboxDropDown() updates the UI and therefore must
551// be called on the main thread.
552AddHistoryItemsToOmniboxDropdown(GetHistoryItemsFromDisk("keyword"));
553```
554
555The code below solves the problem by scheduling a call to
556`GetHistoryItemsFromDisk()` in a thread pool followed by a call to
557`AddHistoryItemsToOmniboxDropdown()` on the origin sequence (the main thread in
558this case). The return value of the first call is automatically provided as
559argument to the second call.
560
561```cpp
Sami Kyostila831c60b2019-07-31 13:31:23562base::PostTaskAndReplyWithResult(
fdoraybacba4a22017-05-10 21:10:00563 FROM_HERE, {base::MayBlock()},
564 base::BindOnce(&GetHistoryItemsFromDisk, "keyword"),
565 base::BindOnce(&AddHistoryItemsToOmniboxDropdown));
566```
567
568## Posting a Task with a Delay
569
570### Posting a One-Off Task with a Delay
571
572To post a task that must run once after a delay expires, use
Gabriel Charette39db4c62019-04-29 19:52:38573`base::PostDelayedTask*()` or `base::TaskRunner::PostDelayedTask()`.
fdoraybacba4a22017-05-10 21:10:00574
575```cpp
Sami Kyostila831c60b2019-07-31 13:31:23576base::PostDelayedTask(
Gabriel Charetteb10aeeb2018-07-26 20:15:00577 FROM_HERE, {base::TaskPriority::BEST_EFFORT}, base::BindOnce(&Task),
fdoraybacba4a22017-05-10 21:10:00578 base::TimeDelta::FromHours(1));
579
580scoped_refptr<base::SequencedTaskRunner> task_runner =
Sami Kyostila831c60b2019-07-31 13:31:23581 base::CreateSequencedTaskRunner({base::TaskPriority::BEST_EFFORT});
fdoraybacba4a22017-05-10 21:10:00582task_runner->PostDelayedTask(
583 FROM_HERE, base::BindOnce(&Task), base::TimeDelta::FromHours(1));
584```
585
586*** note
587**NOTE:** A task that has a 1-hour delay probably doesn’t have to run right away
Gabriel Charetteb10aeeb2018-07-26 20:15:00588when its delay expires. Specify `base::TaskPriority::BEST_EFFORT` to prevent it
fdoraybacba4a22017-05-10 21:10:00589from slowing down the browser when its delay expires.
590***
591
592### Posting a Repeating Task with a Delay
593To post a task that must run at regular intervals,
594use [`base::RepeatingTimer`](https://cs.chromium.org/chromium/src/base/timer/timer.h).
595
596```cpp
597class A {
598 public:
599 ~A() {
600 // The timer is stopped automatically when it is deleted.
601 }
602 void StartDoingStuff() {
603 timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1),
604 this, &MyClass::DoStuff);
605 }
606 void StopDoingStuff() {
607 timer_.Stop();
608 }
609 private:
610 void DoStuff() {
611 // This method is called every second on the sequence that invoked
612 // StartDoingStuff().
613 }
614 base::RepeatingTimer timer_;
615};
616```
617
618## Cancelling a Task
619
620### Using base::WeakPtr
621
622[`base::WeakPtr`](https://cs.chromium.org/chromium/src/base/memory/weak_ptr.h)
623can be used to ensure that any callback bound to an object is canceled when that
624object is destroyed.
625
626```cpp
627int Compute() { … }
628
629class A {
630 public:
fdoraybacba4a22017-05-10 21:10:00631 void ComputeAndStore() {
632 // Schedule a call to Compute() in a thread pool followed by
633 // a call to A::Store() on the current sequence. The call to
634 // A::Store() is canceled when |weak_ptr_factory_| is destroyed.
635 // (guarantees that |this| will not be used-after-free).
636 base::PostTaskAndReplyWithResult(
637 FROM_HERE, base::BindOnce(&Compute),
638 base::BindOnce(&A::Store, weak_ptr_factory_.GetWeakPtr()));
639 }
640
641 private:
642 void Store(int value) { value_ = value; }
643
644 int value_;
Jeremy Roman0dd0b2f2019-07-16 21:00:43645 base::WeakPtrFactory<A> weak_ptr_factory_{this};
fdoraybacba4a22017-05-10 21:10:00646};
647```
648
649Note: `WeakPtr` is not thread-safe: `GetWeakPtr()`, `~WeakPtrFactory()`, and
650`Compute()` (bound to a `WeakPtr`) must all run on the same sequence.
651
652### Using base::CancelableTaskTracker
653
654[`base::CancelableTaskTracker`](https://cs.chromium.org/chromium/src/base/task/cancelable_task_tracker.h)
655allows cancellation to happen on a different sequence than the one on which
656tasks run. Keep in mind that `CancelableTaskTracker` cannot cancel tasks that
657have already started to run.
658
659```cpp
Sami Kyostila831c60b2019-07-31 13:31:23660auto task_runner = base::CreateTaskRunner({base::ThreadPool()});
fdoraybacba4a22017-05-10 21:10:00661base::CancelableTaskTracker cancelable_task_tracker;
662cancelable_task_tracker.PostTask(task_runner.get(), FROM_HERE,
Peter Kasting341e1fb2018-02-24 00:03:01663 base::DoNothing());
fdoraybacba4a22017-05-10 21:10:00664// Cancels Task(), only if it hasn't already started running.
665cancelable_task_tracker.TryCancelAll();
666```
667
668## Testing
669
Gabriel Charette0b20ee62019-09-18 14:06:12670For more details see [Testing Components Which Post
671Tasks](threading_and_tasks_testing.md).
672
fdoraybacba4a22017-05-10 21:10:00673To test code that uses `base::ThreadTaskRunnerHandle`,
674`base::SequencedTaskRunnerHandle` or a function in
Gabriel Charette39db4c62019-04-29 19:52:38675[`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h),
676instantiate a
Gabriel Charette0b20ee62019-09-18 14:06:12677[`base::test::TaskEnvironment`](https://cs.chromium.org/chromium/src/base/test/task_environment.h)
Gabriel Charette39db4c62019-04-29 19:52:38678for the scope of the test. If you need BrowserThreads, use
Gabriel Charette798fde72019-08-20 22:24:04679`content::BrowserTaskEnvironment` instead of
Gabriel Charette694c3c332019-08-19 14:53:05680`base::test::TaskEnvironment`.
fdoraybacba4a22017-05-10 21:10:00681
Gabriel Charette694c3c332019-08-19 14:53:05682Tests can run the `base::test::TaskEnvironment`'s message pump using a
Gabriel Charette39db4c62019-04-29 19:52:38683`base::RunLoop`, which can be made to run until `Quit()` (explicitly or via
684`RunLoop::QuitClosure()`), or to `RunUntilIdle()` ready-to-run tasks and
685immediately return.
Wezd9e4cb772019-01-09 03:07:03686
Gabriel Charette694c3c332019-08-19 14:53:05687TaskEnvironment configures RunLoop::Run() to LOG(FATAL) if it hasn't been
Wezd9e4cb772019-01-09 03:07:03688explicitly quit after TestTimeouts::action_timeout(). This is preferable to
689having the test hang if the code under test fails to trigger the RunLoop to
690quit. The timeout can be overridden with ScopedRunTimeoutForTest.
691
fdoraybacba4a22017-05-10 21:10:00692```cpp
693class MyTest : public testing::Test {
694 public:
695 // ...
696 protected:
Gabriel Charette694c3c332019-08-19 14:53:05697 base::test::TaskEnvironment task_environment_;
fdoraybacba4a22017-05-10 21:10:00698};
699
700TEST(MyTest, MyTest) {
701 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&A));
702 base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE,
703 base::BindOnce(&B));
704 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
705 FROM_HERE, base::BindOnce(&C), base::TimeDelta::Max());
706
707 // This runs the (Thread|Sequenced)TaskRunnerHandle queue until it is empty.
708 // Delayed tasks are not added to the queue until they are ripe for execution.
709 base::RunLoop().RunUntilIdle();
710 // A and B have been executed. C is not ripe for execution yet.
711
712 base::RunLoop run_loop;
713 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&D));
714 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure());
715 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::BindOnce(&E));
716
717 // This runs the (Thread|Sequenced)TaskRunnerHandle queue until QuitClosure is
718 // invoked.
719 run_loop.Run();
720 // D and run_loop.QuitClosure() have been executed. E is still in the queue.
721
Gabriel Charette52fa3ae2019-04-15 21:44:37722 // Tasks posted to thread pool run asynchronously as they are posted.
Sami Kyostila831c60b2019-07-31 13:31:23723 base::PostTask(FROM_HERE, {base::ThreadPool()}, base::BindOnce(&F));
fdoraybacba4a22017-05-10 21:10:00724 auto task_runner =
Sami Kyostila831c60b2019-07-31 13:31:23725 base::CreateSequencedTaskRunner({base::ThreadPool()});
fdoraybacba4a22017-05-10 21:10:00726 task_runner->PostTask(FROM_HERE, base::BindOnce(&G));
727
Gabriel Charette52fa3ae2019-04-15 21:44:37728 // To block until all tasks posted to thread pool are done running:
Gabriel Charette43fd3702019-05-29 16:36:51729 base::ThreadPoolInstance::Get()->FlushForTesting();
fdoraybacba4a22017-05-10 21:10:00730 // F and G have been executed.
731
Sami Kyostila831c60b2019-07-31 13:31:23732 base::PostTaskAndReplyWithResult(
fdoraybacba4a22017-05-10 21:10:00733 FROM_HERE, base::TaskTrait(),
734 base::BindOnce(&H), base::BindOnce(&I));
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 Charette694c3c332019-08-19 14:53:05739 task_environment_.RunUntilIdle();
fdoraybacba4a22017-05-10 21:10:00740 // E, H, I have been executed.
741}
742```
743
Gabriel Charette52fa3ae2019-04-15 21:44:37744## Using ThreadPool in a New Process
fdoraybacba4a22017-05-10 21:10:00745
Gabriel Charette43fd3702019-05-29 16:36:51746ThreadPoolInstance needs to be initialized in a process before the functions in
Gabriel Charette04b138f2018-08-06 00:03:22747[`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h)
Gabriel Charette43fd3702019-05-29 16:36:51748can be used. Initialization of ThreadPoolInstance in the Chrome browser process
749and child processes (renderer, GPU, utility) has already been taken care of. To
750use ThreadPoolInstance in another process, initialize ThreadPoolInstance early
751in the main function:
fdoraybacba4a22017-05-10 21:10:00752
753```cpp
Gabriel Charette43fd3702019-05-29 16:36:51754// This initializes and starts ThreadPoolInstance with default params.
755base::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.
fdoraybacba4a22017-05-10 21:10:00758
Gabriel Charette43fd3702019-05-29 16:36:51759// This initializes ThreadPoolInstance.
760base::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.
764base::ThreadPoolInstance::Get()->Start(params);
Gabriel Charette52fa3ae2019-04-15 21:44:37765// ThreadPool can now create threads and schedule tasks.
fdoraybacba4a22017-05-10 21:10:00766```
767
Gabriel Charette43fd3702019-05-29 16:36:51768And shutdown ThreadPoolInstance late in the main function:
fdoraybacba4a22017-05-10 21:10:00769
770```cpp
Gabriel Charette43fd3702019-05-29 16:36:51771base::ThreadPoolInstance::Get()->Shutdown();
fdoraybacba4a22017-05-10 21:10:00772// 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 Charetteb86e5fe62017-06-08 19:39:28779## TaskRunner ownership (encourage no dependency injection)
Sebastien Marchandc95489b2017-05-25 16:39:34780
781TaskRunners shouldn't be passed through several components. Instead, the
782components that uses a TaskRunner should be the one that creates it.
783
784See [this example](https://codereview.chromium.org/2885173002/) of a
785refactoring where a TaskRunner was passed through a lot of components only to be
786used in an eventual leaf. The leaf can and should now obtain its TaskRunner
787directly from
Gabriel Charette04b138f2018-08-06 00:03:22788[`base/task/post_task.h`](https://cs.chromium.org/chromium/src/base/task/post_task.h).
Gabriel Charetteb86e5fe62017-06-08 19:39:28789
Gabriel Charette694c3c332019-08-19 14:53:05790As mentioned above, `base::test::TaskEnvironment` allows unit tests to
Gabriel Charette39db4c62019-04-29 19:52:38791control tasks posted from underlying TaskRunners. In rare cases where a test
792needs to more precisely control task ordering: dependency injection of
793TaskRunners can be useful. For such cases the preferred approach is the
794following:
Gabriel Charetteb86e5fe62017-06-08 19:39:28795
796```cpp
Gabriel Charette39db4c62019-04-29 19:52:38797class Foo {
Gabriel Charetteb86e5fe62017-06-08 19:39:28798 public:
799
Gabriel Charette39db4c62019-04-29 19:52:38800 // Overrides |background_task_runner_| in tests.
Gabriel Charetteb86e5fe62017-06-08 19:39:28801 void SetBackgroundTaskRunnerForTesting(
Gabriel Charette39db4c62019-04-29 19:52:38802 scoped_refptr<base::SequencedTaskRunner> background_task_runner) {
803 background_task_runner_ = std::move(background_task_runner);
804 }
Gabriel Charetteb86e5fe62017-06-08 19:39:28805
806 private:
michaelpg12c04572017-06-26 23:25:06807 scoped_refptr<base::SequencedTaskRunner> background_task_runner_ =
Sami Kyostila831c60b2019-07-31 13:31:23808 base::CreateSequencedTaskRunner(
Gabriel Charetteb10aeeb2018-07-26 20:15:00809 {base::MayBlock(), base::TaskPriority::BEST_EFFORT});
Gabriel Charetteb86e5fe62017-06-08 19:39:28810}
811```
812
813Note that this still allows removing all layers of plumbing between //chrome and
814that component since unit tests will use the leaf layer directly.
Gabriel Charette8917f4c2018-11-22 15:50:28815
Alex Clarke0dd499562019-10-18 19:45:09816## Old APIs
817
818The codebase contains several old APIs for retrieving the current thread and
819current sequence's task runners. These are being migrated to new APIs and
820shouldn't be used in new code.
821
822[`base::ThreadTaskRunnerHandle`](https://cs.chromium.org/chromium/src/base/threading/thread_task_runner_handle.h)
823returns the default task runner for the current thread. All call sites will be
824migrated to use base::CurrentThread instead.
825
826```cpp
827// The task will run on the current thread in the future.
828base::ThreadTaskRunnerHandle::Get()->PostTask(
829 FROM_HERE, base::BindOnce(&Task));
830```
831
832[`base::SequencedTaskRunnerHandle::Get()`](https://cs.chromium.org/chromium/src/base/threading/sequenced_task_runner_handle.h)
833returns either the thread's default task runner (Browser UI thread, Browser IO
834thread, Blink mail thread) or in a sequenced thread pool task it returns the
835current sequence. All call sites will be migrated to either use
836base::CurrentThread or `base::GetContinuationTaskRunner()` depending on the
837callsite.
838
839```cpp
840// The task will run after any task that has already been posted
841// to the SequencedTaskRunner to which the current task was posted
842// (in particular, it will run after the current task completes).
843// It is also guaranteed that it won’t run concurrently with any
844// task posted to that SequencedTaskRunner.
845base::SequencedTaskRunnerHandle::Get()->
846 PostTask(FROM_HERE, base::BindOnce(&Task));
847```
848
Gabriel Charette8917f4c2018-11-22 15:50:28849## FAQ
850See [Threading and Tasks FAQ](threading_and_tasks_faq.md) for more examples.