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