run_loop.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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_RUN_LOOP_H_
  5. #define BASE_RUN_LOOP_H_
  6. #include <stack>
  7. #include <utility>
  8. #include <vector>
  9. #include "base/base_export.h"
  10. #include "base/callback.h"
  11. #include "base/containers/stack.h"
  12. #include "base/gtest_prod_util.h"
  13. #include "base/memory/ref_counted.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "base/observer_list.h"
  16. #include "base/sequence_checker.h"
  17. #include "base/threading/thread_checker.h"
  18. #include "base/time/time.h"
  19. #include "build/build_config.h"
  20. namespace base {
  21. namespace test {
  22. class ScopedRunLoopTimeout;
  23. class ScopedDisableRunLoopTimeout;
  24. } // namespace test
  25. #if defined(OS_ANDROID)
  26. class MessagePumpForUI;
  27. #endif
  28. #if defined(OS_IOS)
  29. class MessagePumpUIApplication;
  30. #endif
  31. class SingleThreadTaskRunner;
  32. // Helper class to run the RunLoop::Delegate associated with the current thread.
  33. // A RunLoop::Delegate must have been bound to this thread (ref.
  34. // RunLoop::RegisterDelegateForCurrentThread()) prior to using any of RunLoop's
  35. // member and static methods unless explicitly indicated otherwise (e.g.
  36. // IsRunning/IsNestedOnCurrentThread()). RunLoop::Run can only be called once
  37. // per RunLoop lifetime. Create a RunLoop on the stack and call Run/Quit to run
  38. // a nested RunLoop but please avoid nested loops in production code!
  39. class BASE_EXPORT RunLoop {
  40. public:
  41. // The type of RunLoop: a kDefault RunLoop at the top-level (non-nested) will
  42. // process system and application tasks assigned to its Delegate. When nested
  43. // however a kDefault RunLoop will only process system tasks while a
  44. // kNestableTasksAllowed RunLoop will continue to process application tasks
  45. // even if nested.
  46. //
  47. // This is relevant in the case of recursive RunLoops. Some unwanted run loops
  48. // may occur when using common controls or printer functions. By default,
  49. // recursive task processing is disabled.
  50. //
  51. // In general, nestable RunLoops are to be avoided. They are dangerous and
  52. // difficult to get right, so please use with extreme caution.
  53. //
  54. // A specific example where this makes a difference is:
  55. // - The thread is running a RunLoop.
  56. // - It receives a task #1 and executes it.
  57. // - The task #1 implicitly starts a RunLoop, like a MessageBox in the unit
  58. // test. This can also be StartDoc or GetSaveFileName.
  59. // - The thread receives a task #2 before or while in this second RunLoop.
  60. // - With a kNestableTasksAllowed RunLoop, the task #2 will run right away.
  61. // Otherwise, it will get executed right after task #1 completes in the main
  62. // RunLoop.
  63. enum class Type {
  64. kDefault,
  65. kNestableTasksAllowed,
  66. };
  67. explicit RunLoop(Type type = Type::kDefault);
  68. RunLoop(const RunLoop&) = delete;
  69. RunLoop& operator=(const RunLoop&) = delete;
  70. ~RunLoop();
  71. // Run the current RunLoop::Delegate. This blocks until Quit is called
  72. // (directly or by running the RunLoop::QuitClosure).
  73. void Run();
  74. // Run the current RunLoop::Delegate until it doesn't find any tasks or
  75. // messages in its queue (it goes idle).
  76. // WARNING #1: This may run long (flakily timeout) and even never return! Do
  77. // not use this when repeating tasks such as animated web pages
  78. // are present.
  79. // WARNING #2: This may return too early! For example, if used to run until an
  80. // incoming event has occurred but that event depends on a task in
  81. // a different queue -- e.g. another TaskRunner or a system event.
  82. // Per the warnings above, this tends to lead to flaky tests; prefer
  83. // QuitClosure()+Run() when at all possible.
  84. void RunUntilIdle();
  85. bool running() const {
  86. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  87. return running_;
  88. }
  89. // Quit() transitions this RunLoop to a state where no more tasks will be
  90. // allowed to run at the run-loop-level of this RunLoop. If invoked from the
  91. // owning thread, the effect is immediate; otherwise it is thread-safe but
  92. // asynchronous. When the transition takes effect, the underlying message loop
  93. // quits this run-loop-level if it is topmost (otherwise the desire to quit
  94. // this level is saved until run-levels nested above it are quit).
  95. //
  96. // QuitWhenIdle() results in this RunLoop returning true from
  97. // ShouldQuitWhenIdle() at this run-level (the delegate decides when "idle" is
  98. // reached). This is also thread-safe.
  99. //
  100. // There can be other nested RunLoops servicing the same task queue. As
  101. // mentioned above, quitting one RunLoop has no bearing on the others. Hence,
  102. // you may never assume that a call to Quit() will terminate the underlying
  103. // message loop. If a nested RunLoop continues running, the target may NEVER
  104. // terminate.
  105. void Quit();
  106. void QuitWhenIdle();
  107. // Returns a RepeatingClosure that safely calls Quit() or QuitWhenIdle() (has
  108. // no effect if the RunLoop instance is gone).
  109. //
  110. // The closures must be obtained from the thread owning the RunLoop but may
  111. // then be invoked from any thread.
  112. //
  113. // Returned closures may be safely:
  114. // * Passed to other threads.
  115. // * Run() from other threads, though this will quit the RunLoop
  116. // asynchronously.
  117. // * Run() after the RunLoop has stopped or been destroyed, in which case
  118. // they are a no-op).
  119. // * Run() before RunLoop::Run(), in which case RunLoop::Run() returns
  120. // immediately."
  121. //
  122. // Example:
  123. // RunLoop run_loop;
  124. // DoFooAsyncAndNotify(run_loop.QuitClosure());
  125. // run_loop.Run();
  126. //
  127. // Note that Quit() itself is thread-safe and may be invoked directly if you
  128. // have access to the RunLoop reference from another thread (e.g. from a
  129. // capturing lambda or test observer).
  130. RepeatingClosure QuitClosure();
  131. RepeatingClosure QuitWhenIdleClosure();
  132. // Returns true if there is an active RunLoop on this thread.
  133. // Safe to call before RegisterDelegateForCurrentThread().
  134. static bool IsRunningOnCurrentThread();
  135. // Returns true if there is an active RunLoop on this thread and it's nested
  136. // within another active RunLoop.
  137. // Safe to call before RegisterDelegateForCurrentThread().
  138. static bool IsNestedOnCurrentThread();
  139. // A NestingObserver is notified when a nested RunLoop begins and ends.
  140. class BASE_EXPORT NestingObserver {
  141. public:
  142. // Notified before a nested loop starts running work on the current thread.
  143. virtual void OnBeginNestedRunLoop() = 0;
  144. // Notified after a nested loop is done running work on the current thread.
  145. virtual void OnExitNestedRunLoop() {}
  146. protected:
  147. virtual ~NestingObserver() = default;
  148. };
  149. static void AddNestingObserverOnCurrentThread(NestingObserver* observer);
  150. static void RemoveNestingObserverOnCurrentThread(NestingObserver* observer);
  151. // A RunLoop::Delegate is a generic interface that allows RunLoop to be
  152. // separate from the underlying implementation of the message loop for this
  153. // thread. It holds private state used by RunLoops on its associated thread.
  154. // One and only one RunLoop::Delegate must be registered on a given thread
  155. // via RunLoop::RegisterDelegateForCurrentThread() before RunLoop instances
  156. // and RunLoop static methods can be used on it.
  157. class BASE_EXPORT Delegate {
  158. public:
  159. Delegate();
  160. Delegate(const Delegate&) = delete;
  161. Delegate& operator=(const Delegate&) = delete;
  162. virtual ~Delegate();
  163. // Used by RunLoop to inform its Delegate to Run/Quit. Implementations are
  164. // expected to keep on running synchronously from the Run() call until the
  165. // eventual matching Quit() call or a delay of |timeout| expires. Upon
  166. // receiving a Quit() call or timing out it should return from the Run()
  167. // call as soon as possible without executing remaining tasks/messages.
  168. // Run() calls can nest in which case each Quit() call should result in the
  169. // topmost active Run() call returning. The only other trigger for Run()
  170. // to return is the |should_quit_when_idle_callback_| which the Delegate
  171. // should probe before sleeping when it becomes idle.
  172. // |application_tasks_allowed| is true if this is the first Run() call on
  173. // the stack or it was made from a nested RunLoop of
  174. // Type::kNestableTasksAllowed (otherwise this Run() level should only
  175. // process system tasks).
  176. virtual void Run(bool application_tasks_allowed, TimeDelta timeout) = 0;
  177. virtual void Quit() = 0;
  178. // Invoked right before a RunLoop enters a nested Run() call on this
  179. // Delegate iff this RunLoop is of type kNestableTasksAllowed. The Delegate
  180. // should ensure that the upcoming Run() call will result in processing
  181. // application tasks queued ahead of it without further probing. e.g.
  182. // message pumps on some platforms, like Mac, need an explicit request to
  183. // process application tasks when nested, otherwise they'll only wait for
  184. // system messages.
  185. virtual void EnsureWorkScheduled() = 0;
  186. protected:
  187. // Returns the result of this Delegate's |should_quit_when_idle_callback_|.
  188. // "protected" so it can be invoked only by the Delegate itself.
  189. bool ShouldQuitWhenIdle();
  190. private:
  191. // While the state is owned by the Delegate subclass, only RunLoop can use
  192. // it.
  193. friend class RunLoop;
  194. // A vector-based stack is more memory efficient than the default
  195. // deque-based stack as the active RunLoop stack isn't expected to ever
  196. // have more than a few entries.
  197. using RunLoopStack = stack<RunLoop*, std::vector<RunLoop*>>;
  198. RunLoopStack active_run_loops_;
  199. ObserverList<RunLoop::NestingObserver>::Unchecked nesting_observers_;
  200. #if DCHECK_IS_ON()
  201. bool allow_running_for_testing_ = true;
  202. #endif
  203. // True once this Delegate is bound to a thread via
  204. // RegisterDelegateForCurrentThread().
  205. bool bound_ = false;
  206. // Thread-affine per its use of TLS.
  207. THREAD_CHECKER(bound_thread_checker_);
  208. };
  209. // Registers |delegate| on the current thread. Must be called once and only
  210. // once per thread before using RunLoop methods on it. |delegate| is from then
  211. // on forever bound to that thread (including its destruction).
  212. static void RegisterDelegateForCurrentThread(Delegate* delegate);
  213. // Quits the active RunLoop (when idle) -- there must be one. These were
  214. // introduced as prefered temporary replacements to the long deprecated
  215. // MessageLoop::Quit(WhenIdle)(Closure) methods. Callers should properly plumb
  216. // a reference to the appropriate RunLoop instance (or its QuitClosure)
  217. // instead of using these in order to link Run()/Quit() to a single RunLoop
  218. // instance and increase readability.
  219. static void QuitCurrentDeprecated();
  220. static void QuitCurrentWhenIdleDeprecated();
  221. static RepeatingClosure QuitCurrentWhenIdleClosureDeprecated();
  222. // Run() will DCHECK if called while there's a ScopedDisallowRunningForTesting
  223. // in scope on its thread. This is useful to add safety to some test
  224. // constructs which allow multiple task runners to share the main thread in
  225. // unit tests. While the main thread can be shared by multiple runners to
  226. // deterministically fake multi threading, there can still only be a single
  227. // RunLoop::Delegate per thread and RunLoop::Run() should only be invoked from
  228. // it (or it would result in incorrectly driving TaskRunner A while in
  229. // TaskRunner B's context).
  230. class BASE_EXPORT ScopedDisallowRunningForTesting {
  231. public:
  232. ScopedDisallowRunningForTesting();
  233. ScopedDisallowRunningForTesting(const ScopedDisallowRunningForTesting&) =
  234. delete;
  235. ScopedDisallowRunningForTesting& operator=(
  236. const ScopedDisallowRunningForTesting&) = delete;
  237. ~ScopedDisallowRunningForTesting();
  238. private:
  239. #if DCHECK_IS_ON()
  240. Delegate* current_delegate_;
  241. const bool previous_run_allowance_;
  242. #endif // DCHECK_IS_ON()
  243. };
  244. // Support for //base/test/scoped_run_loop_timeout.h.
  245. // This must be public for access by the implementation code in run_loop.cc.
  246. struct BASE_EXPORT RunLoopTimeout {
  247. RunLoopTimeout();
  248. ~RunLoopTimeout();
  249. TimeDelta timeout;
  250. RepeatingClosure on_timeout;
  251. };
  252. private:
  253. FRIEND_TEST_ALL_PREFIXES(SingleThreadTaskExecutorTypedTest,
  254. RunLoopQuitOrderAfter);
  255. #if defined(OS_ANDROID)
  256. // Android doesn't support the blocking RunLoop::Run, so it calls
  257. // BeforeRun and AfterRun directly.
  258. friend class MessagePumpForUI;
  259. #endif
  260. #if defined(OS_IOS)
  261. // iOS doesn't support the blocking RunLoop::Run, so it calls
  262. // BeforeRun directly.
  263. friend class MessagePumpUIApplication;
  264. #endif
  265. // Support for //base/test/scoped_run_loop_timeout.h.
  266. friend class test::ScopedRunLoopTimeout;
  267. friend class test::ScopedDisableRunLoopTimeout;
  268. static void SetTimeoutForCurrentThread(const RunLoopTimeout* timeout);
  269. static const RunLoopTimeout* GetTimeoutForCurrentThread();
  270. // Return false to abort the Run.
  271. bool BeforeRun();
  272. void AfterRun();
  273. // A cached reference of RunLoop::Delegate for the thread driven by this
  274. // RunLoop for quick access without using TLS (also allows access to state
  275. // from another sequence during Run(), ref. |sequence_checker_| below).
  276. Delegate* const delegate_;
  277. const Type type_;
  278. #if DCHECK_IS_ON()
  279. bool run_called_ = false;
  280. #endif
  281. bool quit_called_ = false;
  282. bool running_ = false;
  283. // Used to record that QuitWhenIdle() was called on this RunLoop, meaning that
  284. // the Delegate should quit Run() once it becomes idle (it's responsible for
  285. // probing this state via ShouldQuitWhenIdle()). This state is stored here
  286. // rather than pushed to Delegate to support nested RunLoops.
  287. bool quit_when_idle_received_ = false;
  288. // True if use of QuitCurrent*Deprecated() is allowed. Taking a Quit*Closure()
  289. // from a RunLoop implicitly sets this to false, so QuitCurrent*Deprecated()
  290. // cannot be used while that RunLoop is being Run().
  291. bool allow_quit_current_deprecated_ = true;
  292. // RunLoop is not thread-safe. Its state/methods, unless marked as such, may
  293. // not be accessed from any other sequence than the thread it was constructed
  294. // on. Exception: RunLoop can be safely accessed from one other sequence (or
  295. // single parallel task) during Run() -- e.g. to Quit() without having to
  296. // plumb ThreatTaskRunnerHandle::Get() throughout a test to repost QuitClosure
  297. // to origin thread.
  298. SEQUENCE_CHECKER(sequence_checker_);
  299. const scoped_refptr<SingleThreadTaskRunner> origin_task_runner_;
  300. // WeakPtrFactory for QuitClosure safety.
  301. WeakPtrFactory<RunLoop> weak_factory_{this};
  302. };
  303. } // namespace base
  304. #endif // BASE_RUN_LOOP_H_