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.
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/ref_counted.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 defined(OS_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 // A vector-based stack is more memory efficient than the default
231 // deque-based stack as the active RunLoop stack isn't expected to ever
232 // have more than a few entries.
233 using RunLoopStack = stack<RunLoop*, std::vector<RunLoop*>>;
235 RunLoopStack active_run_loops_;
236 ObserverList<RunLoop::NestingObserver>::Unchecked nesting_observers_;
239 bool allow_running_for_testing_ = true;
242 // True once this Delegate is bound to a thread via
243 // RegisterDelegateForCurrentThread().
246 // Thread-affine per its use of TLS.
247 THREAD_CHECKER(bound_thread_checker_);
250 // Registers |delegate| on the current thread. Must be called once and only
251 // once per thread before using RunLoop methods on it. |delegate| is from then
252 // on forever bound to that thread (including its destruction).
253 static void RegisterDelegateForCurrentThread(Delegate* delegate);
255 // Quits the active RunLoop (when idle) -- there must be one. These were
256 // introduced as prefered temporary replacements to the long deprecated
257 // MessageLoop::Quit(WhenIdle)(Closure) methods. Callers should properly plumb
258 // a reference to the appropriate RunLoop instance (or its QuitClosure)
259 // instead of using these in order to link Run()/Quit() to a single RunLoop
260 // instance and increase readability.
261 static void QuitCurrentDeprecated();
262 static void QuitCurrentWhenIdleDeprecated();
263 static RepeatingClosure QuitCurrentWhenIdleClosureDeprecated();
265 // Run() will DCHECK if called while there's a ScopedDisallowRunning
266 // in scope on its thread. This is useful to add safety to some test
267 // constructs which allow multiple task runners to share the main thread in
268 // unit tests. While the main thread can be shared by multiple runners to
269 // deterministically fake multi threading, there can still only be a single
270 // RunLoop::Delegate per thread and RunLoop::Run() should only be invoked from
271 // it (or it would result in incorrectly driving TaskRunner A while in
272 // TaskRunner B's context).
273 class BASE_EXPORT ScopedDisallowRunning {
275 ScopedDisallowRunning();
276 ScopedDisallowRunning(const ScopedDisallowRunning&) = delete;
277 ScopedDisallowRunning& operator=(const ScopedDisallowRunning&) = delete;
278 ~ScopedDisallowRunning();
282 Delegate* current_delegate_;
283 const bool previous_run_allowance_;
284 #endif // DCHECK_IS_ON()
287 // Support for //base/test/scoped_run_loop_timeout.h.
288 // This must be public for access by the implementation code in run_loop.cc.
289 struct BASE_EXPORT RunLoopTimeout {
293 RepeatingCallback<void(const Location&)> on_timeout;
297 FRIEND_TEST_ALL_PREFIXES(SingleThreadTaskExecutorTypedTest,
298 RunLoopQuitOrderAfter);
300 #if defined(OS_ANDROID)
301 // Android doesn't support the blocking RunLoop::Run, so it calls
302 // BeforeRun and AfterRun directly.
303 friend class MessagePumpForUI;
307 // EFL doesn't support the blocking RunLoop::Run, so it calls
308 // BeforeRun directly.
309 friend class base::MessagePumpForUIEfl;
313 // iOS doesn't support the blocking RunLoop::Run, so it calls
314 // BeforeRun directly.
315 friend class MessagePumpUIApplication;
318 // Support for //base/test/scoped_run_loop_timeout.h.
319 friend class test::ScopedRunLoopTimeout;
320 friend class test::ScopedDisableRunLoopTimeout;
322 static void SetTimeoutForCurrentThread(const RunLoopTimeout* timeout);
323 static const RunLoopTimeout* GetTimeoutForCurrentThread();
325 // Return false to abort the Run.
329 // A cached reference of RunLoop::Delegate for the thread driven by this
330 // RunLoop for quick access without using TLS (also allows access to state
331 // from another sequence during Run(), ref. |sequence_checker_| below).
332 Delegate* const delegate_;
337 bool run_allowed_ = true;
340 bool quit_called_ = false;
341 bool running_ = false;
343 // Used to record that QuitWhenIdle() was called on this RunLoop.
344 bool quit_when_idle_called_ = false;
345 // Whether the Delegate should quit Run() once it becomes idle (it's
346 // responsible for probing this state via ShouldQuitWhenIdle()). This state is
347 // stored here rather than pushed to Delegate to support nested RunLoops.
348 bool quit_when_idle_ = false;
350 // True if use of QuitCurrent*Deprecated() is allowed. Taking a Quit*Closure()
351 // from a RunLoop implicitly sets this to false, so QuitCurrent*Deprecated()
352 // cannot be used while that RunLoop is being Run().
353 bool allow_quit_current_deprecated_ = true;
355 // RunLoop is not thread-safe. Its state/methods, unless marked as such, may
356 // not be accessed from any other sequence than the thread it was constructed
357 // on. Exception: RunLoop can be safely accessed from one other sequence (or
358 // single parallel task) during Run() -- e.g. to Quit() without having to
359 // plumb ThreatTaskRunnerHandle::Get() throughout a test to repost QuitClosure
361 SEQUENCE_CHECKER(sequence_checker_);
363 const scoped_refptr<SingleThreadTaskRunner> origin_task_runner_;
365 // WeakPtrFactory for QuitClosure safety.
366 WeakPtrFactory<RunLoop> weak_factory_{this};
371 #endif // BASE_RUN_LOOP_H_