1// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_TASK_POST_TASK_H_
6#define BASE_TASK_POST_TASK_H_
7
8#include <memory>
9#include <utility>
10
11#include "base/base_export.h"
12#include "base/bind.h"
13#include "base/callback.h"
14#include "base/location.h"
15#include "base/memory/ref_counted.h"
16#include "base/post_task_and_reply_with_result_internal.h"
17#include "base/sequenced_task_runner.h"
18#include "base/single_thread_task_runner.h"
19#include "base/task/single_thread_task_runner_thread_mode.h"
20#include "base/task/task_traits.h"
21#include "base/task_runner.h"
22#include "base/time/time.h"
23#include "build/build_config.h"
24
25namespace base {
26
27// This is the interface to post tasks.
28//
29// To post a simple one-off task with default traits:
30// PostTask(FROM_HERE, BindOnce(...));
31//
32// To post a high priority one-off task to respond to a user interaction:
33// PostTaskWithTraits(
34// FROM_HERE,
35// {TaskPriority::USER_BLOCKING},
36// BindOnce(...));
37//
38// To post tasks that must run in sequence with default traits:
39// scoped_refptr<SequencedTaskRunner> task_runner =
40// CreateSequencedTaskRunnerWithTraits(TaskTraits());
41// task_runner->PostTask(FROM_HERE, BindOnce(...));
42// task_runner->PostTask(FROM_HERE, BindOnce(...));
43//
44// To post tasks that may block, must run in sequence and can be skipped on
45// shutdown:
46// scoped_refptr<SequencedTaskRunner> task_runner =
47// CreateSequencedTaskRunnerWithTraits(
48// {MayBlock(), TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
49// task_runner->PostTask(FROM_HERE, BindOnce(...));
50// task_runner->PostTask(FROM_HERE, BindOnce(...));
51//
52// The default traits apply to tasks that:
53// (1) don't block (ref. MayBlock() and WithBaseSyncPrimitives()),
54// (2) prefer inheriting the current priority to specifying their own, and
55// (3) can either block shutdown or be skipped on shutdown
56// (implementation is free to choose a fitting default).
57// Explicit traits must be specified for tasks for which these loose
58// requirements are not sufficient.
59//
60// Tasks posted with only traits defined in base/task/task_traits.h run on
61// threads owned by the registered ThreadPool (i.e. not on the main thread).
62// An embedder (e.g. Chrome) can define additional traits to make tasks run on
63// threads of their choosing. TODO(https://crbug.com/863341): Make this a
64// reality.
65//
66// Tasks posted with the same traits will be scheduled in the order they were
67// posted. IMPORTANT: Please note however that, unless the traits imply a
68// single thread or sequence, this doesn't guarantee any *execution ordering*
69// for tasks posted in a given order (being scheduled first doesn't mean it will
70// run first -- could run in parallel or have its physical thread preempted).
71//
72// Prerequisite: A ThreadPool must have been registered for the current
73// process via ThreadPool::SetInstance() before the functions below are
74// valid. This is typically done during the initialization phase in each
75// process. If your code is not running in that phase, you most likely don't
76// have to worry about this. You will encounter DCHECKs or nullptr dereferences
77// if this is violated. For tests, prefer base::test::ScopedTaskEnvironment.
78
79// Equivalent to calling PostTaskWithTraits with default TaskTraits.
80BASE_EXPORT bool PostTask(const Location& from_here, OnceClosure task);
81
82// Equivalent to calling PostDelayedTaskWithTraits with default TaskTraits.
83//
84// Use PostDelayedTaskWithTraits to specify a BEST_EFFORT priority if the task
85// doesn't have to run as soon as |delay| expires.
86BASE_EXPORT bool PostDelayedTask(const Location& from_here,
87 OnceClosure task,
88 TimeDelta delay);
89
90// Equivalent to calling PostTaskWithTraitsAndReply with default TaskTraits.
91BASE_EXPORT bool PostTaskAndReply(const Location& from_here,
92 OnceClosure task,
93 OnceClosure reply);
94
95// Equivalent to calling PostTaskWithTraitsAndReplyWithResult with default
96// TaskTraits.
97template <typename TaskReturnType, typename ReplyArgType>
98bool PostTaskAndReplyWithResult(const Location& from_here,
99 OnceCallback<TaskReturnType()> task,
100 OnceCallback<void(ReplyArgType)> reply) {
101 return PostTaskWithTraitsAndReplyWithResult(
102 from_here, TaskTraits(), std::move(task), std::move(reply));
103}
104
105// Callback version of PostTaskAndReplyWithResult above.
106// Though RepeatingCallback is convertible to OnceCallback, we need this since
107// we can not use template deduction and object conversion at once on the
108// overload resolution.
109// TODO(tzik): Update all callers of the Callback version to use OnceCallback.
110template <typename TaskReturnType, typename ReplyArgType>
111bool PostTaskAndReplyWithResult(const Location& from_here,
112 Callback<TaskReturnType()> task,
113 Callback<void(ReplyArgType)> reply) {
114 return PostTaskAndReplyWithResult(
115 from_here, OnceCallback<TaskReturnType()>(std::move(task)),
116 OnceCallback<void(ReplyArgType)>(std::move(reply)));
117}
118
119// Posts |task| with specific |traits|. Returns false if the task definitely
120// won't run because of current shutdown state.
121BASE_EXPORT bool PostTaskWithTraits(const Location& from_here,
122 const TaskTraits& traits,
123 OnceClosure task);
124
125// Posts |task| with specific |traits|. |task| will not run before |delay|
126// expires. Returns false if the task definitely won't run because of current
127// shutdown state.
128//
129// Specify a BEST_EFFORT priority via |traits| if the task doesn't have to run
130// as soon as |delay| expires.
131BASE_EXPORT bool PostDelayedTaskWithTraits(const Location& from_here,
132 const TaskTraits& traits,
133 OnceClosure task,
134 TimeDelta delay);
135
136// Posts |task| with specific |traits| and posts |reply| on the caller's
137// execution context (i.e. same sequence or thread and same TaskTraits if
138// applicable) when |task| completes. Returns false if the task definitely won't
139// run because of current shutdown state. Can only be called when
140// SequencedTaskRunnerHandle::IsSet().
141BASE_EXPORT bool PostTaskWithTraitsAndReply(const Location& from_here,
142 const TaskTraits& traits,
143 OnceClosure task,
144 OnceClosure reply);
145
146// Posts |task| with specific |traits| and posts |reply| with the return value
147// of |task| as argument on the caller's execution context (i.e. same sequence
148// or thread and same TaskTraits if applicable) when |task| completes. Returns
149// false if the task definitely won't run because of current shutdown state. Can
150// only be called when SequencedTaskRunnerHandle::IsSet().
151template <typename TaskReturnType, typename ReplyArgType>
152bool PostTaskWithTraitsAndReplyWithResult(
153 const Location& from_here,
154 const TaskTraits& traits,
155 OnceCallback<TaskReturnType()> task,
156 OnceCallback<void(ReplyArgType)> reply) {
157 auto* result = new std::unique_ptr<TaskReturnType>();
158 return PostTaskWithTraitsAndReply(
159 from_here, traits,
160 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
161 result),
162 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
163 std::move(reply), Owned(result)));
164}
165
166// Callback version of PostTaskWithTraitsAndReplyWithResult above.
167// Though RepeatingCallback is convertible to OnceCallback, we need this since
168// we can not use template deduction and object conversion at once on the
169// overload resolution.
170// TODO(tzik): Update all callers of the Callback version to use OnceCallback.
171template <typename TaskReturnType, typename ReplyArgType>
172bool PostTaskWithTraitsAndReplyWithResult(const Location& from_here,
173 const TaskTraits& traits,
174 Callback<TaskReturnType()> task,
175 Callback<void(ReplyArgType)> reply) {
176 return PostTaskWithTraitsAndReplyWithResult(
177 from_here, traits, OnceCallback<TaskReturnType()>(std::move(task)),
178 OnceCallback<void(ReplyArgType)>(std::move(reply)));
179}
180
181// Returns a TaskRunner whose PostTask invocations result in scheduling tasks
182// using |traits|. Tasks may run in any order and in parallel.
183BASE_EXPORT scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(
184 const TaskTraits& traits);
185
186// Returns a SequencedTaskRunner whose PostTask invocations result in scheduling
187// tasks using |traits|. Tasks run one at a time in posting order.
188BASE_EXPORT scoped_refptr<SequencedTaskRunner>
189CreateSequencedTaskRunnerWithTraits(const TaskTraits& traits);
190
191// Returns a SingleThreadTaskRunner whose PostTask invocations result in
192// scheduling tasks using |traits| on a thread determined by |thread_mode|. See
193// base/task/single_thread_task_runner_thread_mode.h for |thread_mode| details.
194// If |traits| identifies an existing thread,
195// SingleThreadTaskRunnerThreadMode::SHARED must be used. Tasks run on a single
196// thread in posting order.
197//
198// If all you need is to make sure that tasks don't run concurrently (e.g.
199// because they access a data structure which is not thread-safe), use
200// CreateSequencedTaskRunnerWithTraits(). Only use this if you rely on a thread-
201// affine API (it might be safer to assume thread-affinity when dealing with
202// under-documented third-party APIs, e.g. other OS') or share data across tasks
203// using thread-local storage.
204BASE_EXPORT scoped_refptr<SingleThreadTaskRunner>
205CreateSingleThreadTaskRunnerWithTraits(
206 const TaskTraits& traits,
207 SingleThreadTaskRunnerThreadMode thread_mode =
208 SingleThreadTaskRunnerThreadMode::SHARED);
209
210#if defined(OS_WIN)
211// Returns a SingleThreadTaskRunner whose PostTask invocations result in
212// scheduling tasks using |traits| in a COM Single-Threaded Apartment on a
213// thread determined by |thread_mode|. See
214// base/task/single_thread_task_runner_thread_mode.h for |thread_mode| details.
215// If |traits| identifies an existing thread,
216// SingleThreadTaskRunnerThreadMode::SHARED must be used. Tasks run in the same
217// Single-Threaded Apartment in posting order for the returned
218// SingleThreadTaskRunner. There is not necessarily a one-to-one correspondence
219// between SingleThreadTaskRunners and Single-Threaded Apartments. The
220// implementation is free to share apartments or create new apartments as
221// necessary. In either case, care should be taken to make sure COM pointers are
222// not smuggled across apartments.
223BASE_EXPORT scoped_refptr<SingleThreadTaskRunner>
224CreateCOMSTATaskRunnerWithTraits(const TaskTraits& traits,
225 SingleThreadTaskRunnerThreadMode thread_mode =
226 SingleThreadTaskRunnerThreadMode::SHARED);
227#endif // defined(OS_WIN)
228
229} // namespace base
230
231#endif // BASE_TASK_POST_TASK_H_
232