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 { 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, 105 // weak_ptr_factory_.GetWeakPtr(), buffer)); 106 // } 107 // 108 // private: 109 // void OnDataReceived(scoped_refptr<DataBuffer> buffer) { 110 // // Do something with buffer. 111 // } 112 // base::WeakPtrFactory<DataLoader> weak_ptr_factory_{this}; 113 // }; 114 // 115 // 116 // Things to notice: 117 // * Results of |task| are shared with |reply| by binding a shared argument 118 // (a DataBuffer instance). 119 // * The DataLoader object has no special thread safety. 120 // * The DataLoader object can be deleted while |task| is still running, 121 // and the reply will cancel itself safely because it is bound to a 122 // WeakPtr<>. 123 bool PostTaskAndReply(const Location& from_here, 124 OnceClosure task, 125 OnceClosure reply); 126 127 // When you have these methods 128 // 129 // R DoWorkAndReturn(); 130 // void Callback(const R& result); 131 // 132 // and want to call them in a PostTaskAndReply kind of fashion where the 133 // result of DoWorkAndReturn is passed to the Callback, you can use 134 // PostTaskAndReplyWithResult as in this example: 135 // 136 // PostTaskAndReplyWithResult( 137 // target_thread_.task_runner(), 138 // FROM_HERE, 139 // BindOnce(&DoWorkAndReturn), 140 // BindOnce(&Callback)); 141 // 142 // Templating on the types of `task` and `reply` allows template matching to 143 // work for both base::RepeatingCallback and base::OnceCallback in each case. 144 template <typename TaskReturnType, 145 typename ReplyArgType, 146 template <typename> 147 class TaskCallbackType, 148 template <typename> 149 class ReplyCallbackType> requires(IsBaseCallback<TaskCallbackType<void ()>> && IsBaseCallback<ReplyCallbackType<void ()>>)150 requires(IsBaseCallback<TaskCallbackType<void()>> && 151 IsBaseCallback<ReplyCallbackType<void()>>) 152 bool PostTaskAndReplyWithResult(const Location& from_here, 153 TaskCallbackType<TaskReturnType()> task, 154 ReplyCallbackType<void(ReplyArgType)> reply) { 155 DCHECK(task); 156 DCHECK(reply); 157 // std::unique_ptr used to avoid the need of a default constructor. 158 auto* result = new std::unique_ptr<TaskReturnType>(); 159 return PostTaskAndReply( 160 from_here, 161 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, 162 std::move(task), result), 163 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>, 164 std::move(reply), Owned(result))); 165 } 166 167 protected: 168 friend struct TaskRunnerTraits; 169 170 TaskRunner(); 171 virtual ~TaskRunner(); 172 173 // Called when this object should be destroyed. By default simply 174 // deletes |this|, but can be overridden to do something else, like 175 // delete on a certain thread. 176 virtual void OnDestruct() const; 177 }; 178 179 struct BASE_EXPORT TaskRunnerTraits { 180 static void Destruct(const TaskRunner* task_runner); 181 }; 182 183 } // namespace base 184 185 #endif // BASE_TASK_TASK_RUNNER_H_ 186