run_loop.h 15 KB

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