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/check.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/time/time.h"
21 struct TaskRunnerTraits;
23 // A TaskRunner is an object that runs posted tasks (in the form of
24 // OnceClosure objects). The TaskRunner interface provides a way of
25 // decoupling task posting from the mechanics of how each task will be
26 // run. TaskRunner provides very weak guarantees as to how posted
27 // tasks are run (or if they're run at all). In particular, it only
30 // - Posting a task will not run it synchronously. That is, no
31 // Post*Task method will call task.Run() directly.
33 // - Increasing the delay can only delay when the task gets run.
34 // That is, increasing the delay may not affect when the task gets
35 // run, or it could make it run later than it normally would, but
36 // it won't make it run earlier than it normally would.
38 // TaskRunner does not guarantee the order in which posted tasks are
39 // run, whether tasks overlap, or whether they're run on a particular
40 // thread. Also it does not guarantee a memory model for shared data
41 // between tasks. (In other words, you should use your own
42 // synchronization/locking primitives if you need to share data
45 // Implementations of TaskRunner should be thread-safe in that all
46 // methods must be safe to call on any thread. Ownership semantics
47 // for TaskRunners are in general not clear, which is why the
48 // interface itself is RefCountedThreadSafe.
50 // Some theoretical implementations of TaskRunner:
52 // - A TaskRunner that uses a thread pool to run posted tasks.
54 // - A TaskRunner that, for each task, spawns a non-joinable thread
55 // to run that task and immediately quit.
57 // - A TaskRunner that stores the list of posted tasks and has a
58 // method Run() that runs each runnable task in random order.
59 class BASE_EXPORT TaskRunner
60 : public RefCountedThreadSafe<TaskRunner, TaskRunnerTraits> {
62 // Posts the given task to be run. Returns true if the task may be
63 // run at some point in the future, and false if the task definitely
66 // Equivalent to PostDelayedTask(from_here, task, 0).
67 bool PostTask(const Location& from_here, OnceClosure task);
69 // Like PostTask, but tries to run the posted task only after |delay_ms|
70 // has passed. Implementations should use a tick clock, rather than wall-
71 // clock time, to implement |delay|.
72 virtual bool PostDelayedTask(const Location& from_here,
74 base::TimeDelta delay) = 0;
76 // Posts |task| on the current TaskRunner. On completion, |reply|
77 // is posted to the thread that called PostTaskAndReply(). Both
78 // |task| and |reply| are guaranteed to be deleted on the thread
79 // from which PostTaskAndReply() is invoked. This allows objects
80 // that must be deleted on the originating thread to be bound into
81 // the |task| and |reply| OnceClosures. In particular, it can be useful
82 // to use WeakPtr<> in the |reply| OnceClosure so that the reply
83 // operation can be canceled. See the following pseudo-code:
85 // class DataBuffer : public RefCountedThreadSafe<DataBuffer> {
87 // // Called to add data into a buffer.
88 // void AddData(void* buf, size_t length);
93 // class DataLoader : public SupportsWeakPtr<DataLoader> {
96 // scoped_refptr<DataBuffer> buffer = new DataBuffer();
97 // target_thread_.task_runner()->PostTaskAndReply(
99 // base::BindOnce(&DataBuffer::AddData, buffer),
100 // base::BindOnce(&DataLoader::OnDataReceived, AsWeakPtr(), buffer));
104 // void OnDataReceived(scoped_refptr<DataBuffer> buffer) {
105 // // Do something with buffer.
111 // * Results of |task| are shared with |reply| by binding a shared argument
112 // (a DataBuffer instance).
113 // * The DataLoader object has no special thread safety.
114 // * The DataLoader object can be deleted while |task| is still running,
115 // and the reply will cancel itself safely because it is bound to a
117 bool PostTaskAndReply(const Location& from_here,
121 // When you have these methods
123 // R DoWorkAndReturn();
124 // void Callback(const R& result);
126 // and want to call them in a PostTaskAndReply kind of fashion where the
127 // result of DoWorkAndReturn is passed to the Callback, you can use
128 // PostTaskAndReplyWithResult as in this example:
130 // PostTaskAndReplyWithResult(
131 // target_thread_.task_runner(),
133 // BindOnce(&DoWorkAndReturn),
134 // BindOnce(&Callback));
135 template <typename TaskReturnType, typename ReplyArgType>
136 bool PostTaskAndReplyWithResult(const Location& from_here,
137 OnceCallback<TaskReturnType()> task,
138 OnceCallback<void(ReplyArgType)> reply) {
141 // std::unique_ptr used to avoid the need of a default constructor.
142 auto* result = new std::unique_ptr<TaskReturnType>();
143 return PostTaskAndReply(
145 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>,
146 std::move(task), result),
147 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
148 std::move(reply), Owned(result)));
152 friend struct TaskRunnerTraits;
155 virtual ~TaskRunner();
157 // Called when this object should be destroyed. By default simply
158 // deletes |this|, but can be overridden to do something else, like
159 // delete on a certain thread.
160 virtual void OnDestruct() const;
163 struct BASE_EXPORT TaskRunnerTraits {
164 static void Destruct(const TaskRunner* task_runner);
169 #endif // BASE_TASK_RUNNER_H_