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