sequenced_task_runner.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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_SEQUENCED_TASK_RUNNER_H_
  5. #define BASE_TASK_SEQUENCED_TASK_RUNNER_H_
  6. #include <memory>
  7. #include "base/base_export.h"
  8. #include "base/callback.h"
  9. #include "base/task/delay_policy.h"
  10. #include "base/task/delayed_task_handle.h"
  11. #include "base/task/sequenced_task_runner_helpers.h"
  12. #include "base/task/task_runner.h"
  13. #include "base/types/pass_key.h"
  14. namespace blink {
  15. class LowPrecisionTimer;
  16. class MetronomeSource;
  17. class TimerBase;
  18. class WebRtcTaskQueue;
  19. }
  20. namespace webrtc {
  21. class ThreadWrapper;
  22. } // namespace webrtc
  23. namespace media {
  24. class AlsaPcmOutputStream;
  25. class AlsaPcmInputStream;
  26. class FakeAudioWorker;
  27. } // namespace media
  28. namespace base {
  29. namespace internal {
  30. class DelayTimerBase;
  31. class DelayedTaskManager;
  32. }
  33. class DeadlineTimer;
  34. class MetronomeTimer;
  35. class TimeDelta;
  36. class TimeTicks;
  37. namespace subtle {
  38. // Used to restrict access to PostCancelableDelayedTaskAt() to authorize
  39. // callers.
  40. class PostDelayedTaskPassKey {
  41. private:
  42. // Avoid =default to disallow creation by uniform initialization.
  43. PostDelayedTaskPassKey() {}
  44. friend class base::internal::DelayTimerBase;
  45. friend class base::internal::DelayedTaskManager;
  46. friend class base::DeadlineTimer;
  47. friend class base::MetronomeTimer;
  48. friend class blink::LowPrecisionTimer;
  49. friend class blink::MetronomeSource;
  50. friend class blink::TimerBase;
  51. friend class blink::WebRtcTaskQueue;
  52. friend class PostDelayedTaskPassKeyForTesting;
  53. friend class webrtc::ThreadWrapper;
  54. friend class media::AlsaPcmOutputStream;
  55. friend class media::AlsaPcmInputStream;
  56. friend class media::FakeAudioWorker;
  57. };
  58. class PostDelayedTaskPassKeyForTesting : public PostDelayedTaskPassKey {};
  59. } // namespace subtle
  60. // A SequencedTaskRunner is a subclass of TaskRunner that provides
  61. // additional guarantees on the order that tasks are started, as well
  62. // as guarantees on when tasks are in sequence, i.e. one task finishes
  63. // before the other one starts.
  64. //
  65. // Summary
  66. // -------
  67. // Non-nested tasks with the same delay will run one by one in FIFO
  68. // order.
  69. //
  70. // Detailed guarantees
  71. // -------------------
  72. //
  73. // SequencedTaskRunner also adds additional methods for posting
  74. // non-nestable tasks. In general, an implementation of TaskRunner
  75. // may expose task-running methods which are themselves callable from
  76. // within tasks. A non-nestable task is one that is guaranteed to not
  77. // be run from within an already-running task. Conversely, a nestable
  78. // task (the default) is a task that can be run from within an
  79. // already-running task.
  80. //
  81. // The guarantees of SequencedTaskRunner are as follows:
  82. //
  83. // - Given two tasks T2 and T1, T2 will start after T1 starts if:
  84. //
  85. // * T2 is posted after T1; and
  86. // * T2 has equal or higher delay than T1; and
  87. // * T2 is non-nestable or T1 is nestable.
  88. //
  89. // - If T2 will start after T1 starts by the above guarantee, then
  90. // T2 will start after T1 finishes and is destroyed if:
  91. //
  92. // * T2 is non-nestable, or
  93. // * T1 doesn't call any task-running methods.
  94. //
  95. // - If T2 will start after T1 finishes by the above guarantee, then
  96. // all memory changes in T1 and T1's destruction will be visible
  97. // to T2.
  98. //
  99. // - If T2 runs nested within T1 via a call to the task-running
  100. // method M, then all memory changes in T1 up to the call to M
  101. // will be visible to T2, and all memory changes in T2 will be
  102. // visible to T1 from the return from M.
  103. //
  104. // Note that SequencedTaskRunner does not guarantee that tasks are run
  105. // on a single dedicated thread, although the above guarantees provide
  106. // most (but not all) of the same guarantees. If you do need to
  107. // guarantee that tasks are run on a single dedicated thread, see
  108. // SingleThreadTaskRunner (in single_thread_task_runner.h).
  109. //
  110. // Some corollaries to the above guarantees, assuming the tasks in
  111. // question don't call any task-running methods:
  112. //
  113. // - Tasks posted via PostTask are run in FIFO order.
  114. //
  115. // - Tasks posted via PostNonNestableTask are run in FIFO order.
  116. //
  117. // - Tasks posted with the same delay and the same nestable state
  118. // are run in FIFO order.
  119. //
  120. // - A list of tasks with the same nestable state posted in order of
  121. // non-decreasing delay is run in FIFO order.
  122. //
  123. // - A list of tasks posted in order of non-decreasing delay with at
  124. // most a single change in nestable state from nestable to
  125. // non-nestable is run in FIFO order. (This is equivalent to the
  126. // statement of the first guarantee above.)
  127. //
  128. // Some theoretical implementations of SequencedTaskRunner:
  129. //
  130. // - A SequencedTaskRunner that wraps a regular TaskRunner but makes
  131. // sure that only one task at a time is posted to the TaskRunner,
  132. // with appropriate memory barriers in between tasks.
  133. //
  134. // - A SequencedTaskRunner that, for each task, spawns a joinable
  135. // thread to run that task and immediately quit, and then
  136. // immediately joins that thread.
  137. //
  138. // - A SequencedTaskRunner that stores the list of posted tasks and
  139. // has a method Run() that runs each runnable task in FIFO order
  140. // that can be called from any thread, but only if another
  141. // (non-nested) Run() call isn't already happening.
  142. class BASE_EXPORT SequencedTaskRunner : public TaskRunner {
  143. public:
  144. // The two PostNonNestable*Task methods below are like their
  145. // nestable equivalents in TaskRunner, but they guarantee that the
  146. // posted task will not run nested within an already-running task.
  147. //
  148. // A simple corollary is that posting a task as non-nestable can
  149. // only delay when the task gets run. That is, posting a task as
  150. // non-nestable may not affect when the task gets run, or it could
  151. // make it run later than it normally would, but it won't make it
  152. // run earlier than it normally would.
  153. // TODO(akalin): Get rid of the boolean return value for the methods
  154. // below.
  155. bool PostNonNestableTask(const Location& from_here, OnceClosure task);
  156. virtual bool PostNonNestableDelayedTask(const Location& from_here,
  157. OnceClosure task,
  158. base::TimeDelta delay) = 0;
  159. // Posts the given |task| to be run only after |delay| has passed. Returns a
  160. // handle that can be used to cancel the task. This should not be used
  161. // directly. Consider using higher level timer primitives in
  162. // base/timer/timer.h.
  163. //
  164. // The handle is only valid while the task is pending execution. This means
  165. // that it will be invalid if the posting failed, and will be invalid while
  166. // the task is executing. Calling CancelTask() on an invalid handle is a
  167. // no-op.
  168. //
  169. // This method and the handle it returns are not thread-safe and can only be
  170. // used from the sequence this task runner runs its tasks on.
  171. virtual DelayedTaskHandle PostCancelableDelayedTask(
  172. subtle::PostDelayedTaskPassKey,
  173. const Location& from_here,
  174. OnceClosure task,
  175. TimeDelta delay);
  176. // Posts the given |task| to be run at |delayed_run_time| (or immediately if
  177. // in the past), following |delay_policy|. Returns a handle that can be used
  178. // to cancel the task. This should not be used directly. Consider using higher
  179. // level timer primitives in base/timer/timer.h.
  180. [[nodiscard]] virtual DelayedTaskHandle PostCancelableDelayedTaskAt(
  181. subtle::PostDelayedTaskPassKey,
  182. const Location& from_here,
  183. OnceClosure task,
  184. TimeTicks delayed_run_time,
  185. subtle::DelayPolicy delay_policy);
  186. // Posts the given |task| to be run at |delayed_run_time| (or immediately if
  187. // in the past), following |delay_policy|. This is used by the default
  188. // implementation of PostCancelableDelayedTaskAt(). The default behavior
  189. // subtracts TimeTicks::Now() from |delayed_run_time| to get a delay. See
  190. // base::Timer to post precise/repeating timeouts.
  191. // TODO(1153139): Make pure virtual once all SequencedTaskRunners implement
  192. // this.
  193. virtual bool PostDelayedTaskAt(subtle::PostDelayedTaskPassKey,
  194. const Location& from_here,
  195. OnceClosure task,
  196. TimeTicks delayed_run_time,
  197. subtle::DelayPolicy delay_policy);
  198. // Submits a non-nestable task to delete the given object. Returns
  199. // true if the object may be deleted at some point in the future,
  200. // and false if the object definitely will not be deleted.
  201. template <class T>
  202. bool DeleteSoon(const Location& from_here, const T* object) {
  203. return DeleteOrReleaseSoonInternal(from_here, &DeleteHelper<T>::DoDelete,
  204. object);
  205. }
  206. template <class T>
  207. bool DeleteSoon(const Location& from_here, std::unique_ptr<T> object) {
  208. return DeleteOrReleaseSoonInternal(
  209. from_here, &DeleteUniquePtrHelper<T>::DoDelete, object.release());
  210. }
  211. // Submits a non-nestable task to release the given object.
  212. //
  213. // ReleaseSoon makes sure that the object it the scoped_refptr points to gets
  214. // properly released on the correct thread.
  215. // We apply ReleaseSoon to the rvalue as the side-effects can be unclear to
  216. // the caller if an lvalue is used. That being so, the scoped_refptr should
  217. // always be std::move'd.
  218. // Example use:
  219. //
  220. // scoped_refptr<T> foo_scoped_refptr;
  221. // ...
  222. // task_runner->ReleaseSoon(std::move(foo_scoped_refptr));
  223. template <class T>
  224. void ReleaseSoon(const Location& from_here, scoped_refptr<T>&& object) {
  225. if (!object)
  226. return;
  227. DeleteOrReleaseSoonInternal(from_here, &ReleaseHelper<T>::DoRelease,
  228. object.release());
  229. }
  230. // Returns true iff tasks posted to this TaskRunner are sequenced
  231. // with this call.
  232. //
  233. // In particular:
  234. // - Returns true if this is a SequencedTaskRunner to which the
  235. // current task was posted.
  236. // - Returns true if this is a SequencedTaskRunner bound to the
  237. // same sequence as the SequencedTaskRunner to which the current
  238. // task was posted.
  239. // - Returns true if this is a SingleThreadTaskRunner bound to
  240. // the current thread.
  241. virtual bool RunsTasksInCurrentSequence() const = 0;
  242. protected:
  243. ~SequencedTaskRunner() override = default;
  244. private:
  245. bool DeleteOrReleaseSoonInternal(const Location& from_here,
  246. void (*deleter)(const void*),
  247. const void* object);
  248. };
  249. // Sample usage with std::unique_ptr :
  250. // std::unique_ptr<Foo, base::OnTaskRunnerDeleter> ptr(
  251. // new Foo, base::OnTaskRunnerDeleter(my_task_runner));
  252. //
  253. // For RefCounted see base::RefCountedDeleteOnSequence.
  254. struct BASE_EXPORT OnTaskRunnerDeleter {
  255. explicit OnTaskRunnerDeleter(scoped_refptr<SequencedTaskRunner> task_runner);
  256. ~OnTaskRunnerDeleter();
  257. OnTaskRunnerDeleter(OnTaskRunnerDeleter&&);
  258. OnTaskRunnerDeleter& operator=(OnTaskRunnerDeleter&&);
  259. // For compatibility with std:: deleters.
  260. template <typename T>
  261. void operator()(const T* ptr) {
  262. if (ptr)
  263. task_runner_->DeleteSoon(FROM_HERE, ptr);
  264. }
  265. scoped_refptr<SequencedTaskRunner> task_runner_;
  266. };
  267. } // namespace base
  268. #endif // BASE_TASK_SEQUENCED_TASK_RUNNER_H_