run_loop.h 14 KB

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