task_runner.h 6.5 KB

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