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. 4 5 #ifndef BASE_TASK_RUNNER_H_ 6 #define BASE_TASK_RUNNER_H_ 7 8 #include <stddef.h> 9 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" 18 19 namespace base { 20 21 struct TaskRunnerTraits; 22 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 28 // guarantees: 29 // 30 // - Posting a task will not run it synchronously. That is, no 31 // Post*Task method will call task.Run() directly. 32 // 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. 37 // 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 43 // between tasks.) 44 // 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. 49 // 50 // Some theoretical implementations of TaskRunner: 51 // 52 // - A TaskRunner that uses a thread pool to run posted tasks. 53 // 54 // - A TaskRunner that, for each task, spawns a non-joinable thread 55 // to run that task and immediately quit. 56 // 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> { 61 public: 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 64 // will not be run. 65 // 66 // Equivalent to PostDelayedTask(from_here, task, 0). 67 bool PostTask(const Location& from_here, OnceClosure task); 68 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, 73 OnceClosure task, 74 base::TimeDelta delay) = 0; 75 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: 84 // 85 // class DataBuffer : public RefCountedThreadSafe<DataBuffer> { 86 // public: 87 // // Called to add data into a buffer. 88 // void AddData(void* buf, size_t length); 89 // ... 90 // }; 91 // 92 // 93 // class DataLoader : public SupportsWeakPtr<DataLoader> { 94 // public: 95 // void GetData() { 96 // scoped_refptr<DataBuffer> buffer = new DataBuffer(); 97 // target_thread_.task_runner()->PostTaskAndReply( 98 // FROM_HERE, 99 // base::BindOnce(&DataBuffer::AddData, buffer), 100 // base::BindOnce(&DataLoader::OnDataReceived, AsWeakPtr(), buffer)); 101 // } 102 // 103 // private: 104 // void OnDataReceived(scoped_refptr<DataBuffer> buffer) { 105 // // Do something with buffer. 106 // } 107 // }; 108 // 109 // 110 // Things to notice: 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 116 // WeakPtr<>. 117 bool PostTaskAndReply(const Location& from_here, 118 OnceClosure task, 119 OnceClosure reply); 120 121 // When you have these methods 122 // 123 // R DoWorkAndReturn(); 124 // void Callback(const R& result); 125 // 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: 129 // 130 // PostTaskAndReplyWithResult( 131 // target_thread_.task_runner(), 132 // FROM_HERE, 133 // BindOnce(&DoWorkAndReturn), 134 // BindOnce(&Callback)); 135 template <typename TaskReturnType, typename ReplyArgType> PostTaskAndReplyWithResult(const Location & from_here,OnceCallback<TaskReturnType ()> task,OnceCallback<void (ReplyArgType)> reply)136 bool PostTaskAndReplyWithResult(const Location& from_here, 137 OnceCallback<TaskReturnType()> task, 138 OnceCallback<void(ReplyArgType)> reply) { 139 DCHECK(task); 140 DCHECK(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( 144 from_here, 145 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, 146 std::move(task), result), 147 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>, 148 std::move(reply), Owned(result))); 149 } 150 151 protected: 152 friend struct TaskRunnerTraits; 153 154 TaskRunner(); 155 virtual ~TaskRunner(); 156 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; 161 }; 162 163 struct BASE_EXPORT TaskRunnerTraits { 164 static void Destruct(const TaskRunner* task_runner); 165 }; 166 167 } // namespace base 168 169 #endif // BASE_TASK_RUNNER_H_ 170