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