1 // Copyright 2012 The Chromium Authors 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_TASK_RUNNER_H_ 6 #define BASE_TASK_TASK_RUNNER_H_ 7 8 #include <stddef.h> 9 10 #include "base/base_export.h" 11 #include "base/check.h" 12 #include "base/functional/bind.h" 13 #include "base/functional/callback.h" 14 #include "base/functional/callback_helpers.h" 15 #include "base/location.h" 16 #include "base/memory/ref_counted.h" 17 #include "base/task/post_task_and_reply_with_result_internal.h" 18 19 namespace base { 20 21 struct TaskRunnerTraits; 22 class TimeDelta; 23 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 29 // guarantees: 30 // 31 // - Posting a task will not run it synchronously. That is, no 32 // Post*Task method will call task.Run() directly. 33 // 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. 38 // 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 44 // between tasks.) 45 // 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. 50 // 51 // Some theoretical implementations of TaskRunner: 52 // 53 // - A TaskRunner that uses a thread pool to run posted tasks. 54 // 55 // - A TaskRunner that, for each task, spawns a non-joinable thread 56 // to run that task and immediately quit. 57 // 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> { 62 public: 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 65 // will not be run. 66 // 67 // Equivalent to PostDelayedTask(from_here, task, 0). 68 bool PostTask(const Location& from_here, OnceClosure task); 69 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, 74 OnceClosure task, 75 base::TimeDelta delay) = 0; 76 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: 88 // 89 // class DataBuffer : public RefCountedThreadSafe<DataBuffer> { 90 // public: 91 // // Called to add data into a buffer. 92 // void AddData(void* buf, size_t length); 93 // ... 94 // }; 95 // 96 // 97 // class DataLoader : public SupportsWeakPtr<DataLoader> { 98 // public: 99 // void GetData() { 100 // scoped_refptr<DataBuffer> buffer = new DataBuffer(); 101 // target_thread_.task_runner()->PostTaskAndReply( 102 // FROM_HERE, 103 // base::BindOnce(&DataBuffer::AddData, buffer), 104 // base::BindOnce(&DataLoader::OnDataReceived, AsWeakPtr(), buffer)); 105 // } 106 // 107 // private: 108 // void OnDataReceived(scoped_refptr<DataBuffer> buffer) { 109 // // Do something with buffer. 110 // } 111 // }; 112 // 113 // 114 // Things to notice: 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 120 // WeakPtr<>. 121 bool PostTaskAndReply(const Location& from_here, 122 OnceClosure task, 123 OnceClosure reply); 124 125 // When you have these methods 126 // 127 // R DoWorkAndReturn(); 128 // void Callback(const R& result); 129 // 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: 133 // 134 // PostTaskAndReplyWithResult( 135 // target_thread_.task_runner(), 136 // FROM_HERE, 137 // BindOnce(&DoWorkAndReturn), 138 // BindOnce(&Callback)); 139 // 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, 144 template <typename> 145 class TaskCallbackType, 146 template <typename> 147 class ReplyCallbackType, 148 typename = EnableIfIsBaseCallback<TaskCallbackType>, 149 typename = EnableIfIsBaseCallback<ReplyCallbackType>> PostTaskAndReplyWithResult(const Location & from_here,TaskCallbackType<TaskReturnType ()> task,ReplyCallbackType<void (ReplyArgType)> reply)150 bool PostTaskAndReplyWithResult(const Location& from_here, 151 TaskCallbackType<TaskReturnType()> task, 152 ReplyCallbackType<void(ReplyArgType)> reply) { 153 DCHECK(task); 154 DCHECK(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( 158 from_here, 159 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, 160 std::move(task), result), 161 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>, 162 std::move(reply), Owned(result))); 163 } 164 165 protected: 166 friend struct TaskRunnerTraits; 167 168 TaskRunner(); 169 virtual ~TaskRunner(); 170 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; 175 }; 176 177 struct BASE_EXPORT TaskRunnerTraits { 178 static void Destruct(const TaskRunner* task_runner); 179 }; 180 181 } // namespace base 182 183 #endif // BASE_TASK_TASK_RUNNER_H_ 184