1 // Copyright (c) 2012 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.
5 #ifndef BASE_TASK_RUNNER_H_
6 #define BASE_TASK_RUNNER_H_
10 #include "base/base_export.h"
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/callback_helpers.h"
14 #include "base/check.h"
15 #include "base/location.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/post_task_and_reply_with_result_internal.h"
18 #include "base/time/time.h"
22 struct TaskRunnerTraits;
24 // A TaskRunner is an object that runs posted tasks (in the form of
25 // OnceClosure objects). The TaskRunner interface provides a way of
26 // decoupling task posting from the mechanics of how each task will be
27 // run. TaskRunner provides very weak guarantees as to how posted
28 // tasks are run (or if they're run at all). In particular, it only
31 // - Posting a task will not run it synchronously. That is, no
32 // Post*Task method will call task.Run() directly.
34 // - Increasing the delay can only delay when the task gets run.
35 // That is, increasing the delay may not affect when the task gets
36 // run, or it could make it run later than it normally would, but
37 // it won't make it run earlier than it normally would.
39 // TaskRunner does not guarantee the order in which posted tasks are
40 // run, whether tasks overlap, or whether they're run on a particular
41 // thread. Also it does not guarantee a memory model for shared data
42 // between tasks. (In other words, you should use your own
43 // synchronization/locking primitives if you need to share data
46 // Implementations of TaskRunner should be thread-safe in that all
47 // methods must be safe to call on any thread. Ownership semantics
48 // for TaskRunners are in general not clear, which is why the
49 // interface itself is RefCountedThreadSafe.
51 // Some theoretical implementations of TaskRunner:
53 // - A TaskRunner that uses a thread pool to run posted tasks.
55 // - A TaskRunner that, for each task, spawns a non-joinable thread
56 // to run that task and immediately quit.
58 // - A TaskRunner that stores the list of posted tasks and has a
59 // method Run() that runs each runnable task in random order.
60 class BASE_EXPORT TaskRunner
61 : public RefCountedThreadSafe<TaskRunner, TaskRunnerTraits> {
63 // Posts the given task to be run. Returns true if the task may be
64 // run at some point in the future, and false if the task definitely
67 // Equivalent to PostDelayedTask(from_here, task, 0).
68 bool PostTask(const Location& from_here, OnceClosure task);
70 // Like PostTask, but tries to run the posted task only after |delay_ms|
71 // has passed. Implementations should use a tick clock, rather than wall-
72 // clock time, to implement |delay|.
73 virtual bool PostDelayedTask(const Location& from_here,
75 base::TimeDelta delay) = 0;
77 // Posts |task| on the current TaskRunner. On completion, |reply| is posted
78 // to the sequence that called PostTaskAndReply(). On the success case,
79 // |task| is destroyed on the target sequence and |reply| is destroyed on the
80 // originating sequence immediately after their invocation. If an error
81 // happened on the onward PostTask, both |task| and |reply| are destroyed on
82 // the originating sequence, and on an error on the backward PostTask, |reply|
83 // is leaked rather than being destroyed on the wrong sequence. This allows
84 // objects that must be deleted on the originating sequence to be bound into
85 // the |reply| Closures. In particular, it can be useful to use WeakPtr<> in
86 // the |reply| Closure so that the reply operation can be canceled. See the
87 // following pseudo-code:
89 // class DataBuffer : public RefCountedThreadSafe<DataBuffer> {
91 // // Called to add data into a buffer.
92 // void AddData(void* buf, size_t length);
97 // class DataLoader : public SupportsWeakPtr<DataLoader> {
100 // scoped_refptr<DataBuffer> buffer = new DataBuffer();
101 // target_thread_.task_runner()->PostTaskAndReply(
103 // base::BindOnce(&DataBuffer::AddData, buffer),
104 // base::BindOnce(&DataLoader::OnDataReceived, AsWeakPtr(), buffer));
108 // void OnDataReceived(scoped_refptr<DataBuffer> buffer) {
109 // // Do something with buffer.
115 // * Results of |task| are shared with |reply| by binding a shared argument
116 // (a DataBuffer instance).
117 // * The DataLoader object has no special thread safety.
118 // * The DataLoader object can be deleted while |task| is still running,
119 // and the reply will cancel itself safely because it is bound to a
121 bool PostTaskAndReply(const Location& from_here,
125 // When you have these methods
127 // R DoWorkAndReturn();
128 // void Callback(const R& result);
130 // and want to call them in a PostTaskAndReply kind of fashion where the
131 // result of DoWorkAndReturn is passed to the Callback, you can use
132 // PostTaskAndReplyWithResult as in this example:
134 // PostTaskAndReplyWithResult(
135 // target_thread_.task_runner(),
137 // BindOnce(&DoWorkAndReturn),
138 // BindOnce(&Callback));
140 // Templating on the types of `task` and `reply` allows template matching to
141 // work for both base::RepeatingCallback and base::OnceCallback in each case.
142 template <typename TaskReturnType,
143 typename ReplyArgType,
145 class TaskCallbackType,
147 class ReplyCallbackType,
148 typename = EnableIfIsBaseCallback<TaskCallbackType>,
149 typename = EnableIfIsBaseCallback<ReplyCallbackType>>
150 bool PostTaskAndReplyWithResult(const Location& from_here,
151 TaskCallbackType<TaskReturnType()> task,
152 ReplyCallbackType<void(ReplyArgType)> reply) {
155 // std::unique_ptr used to avoid the need of a default constructor.
156 auto* result = new std::unique_ptr<TaskReturnType>();
157 return PostTaskAndReply(
159 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>,
160 std::move(task), result),
161 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
162 std::move(reply), Owned(result)));
166 friend struct TaskRunnerTraits;
169 virtual ~TaskRunner();
171 // Called when this object should be destroyed. By default simply
172 // deletes |this|, but can be overridden to do something else, like
173 // delete on a certain thread.
174 virtual void OnDestruct() const;
177 struct BASE_EXPORT TaskRunnerTraits {
178 static void Destruct(const TaskRunner* task_runner);
183 #endif // BASE_TASK_RUNNER_H_