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