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/macros.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/observer_list.h"
18 #include "base/sequence_checker.h"
19 #include "base/threading/thread_checker.h"
20 #include "build/build_config.h"
23 #if defined(OS_ANDROID)
24 class MessagePumpForUI;
28 class MessagePumpForUIEfl;
32 class MessagePumpUIApplication;
35 class SingleThreadTaskRunner;
37 // Helper class to run the RunLoop::Delegate associated with the current thread.
38 // A RunLoop::Delegate must have been bound to this thread (ref.
39 // RunLoop::RegisterDelegateForCurrentThread()) prior to using any of RunLoop's
40 // member and static methods unless explicitly indicated otherwise (e.g.
41 // IsRunning/IsNestedOnCurrentThread()). RunLoop::Run can only be called once
42 // per RunLoop lifetime. Create a RunLoop on the stack and call Run/Quit to run
43 // a nested RunLoop but please do not use nested loops in production code!
44 class BASE_EXPORT RunLoop {
46 // The type of RunLoop: a kDefault RunLoop at the top-level (non-nested) will
47 // process system and application tasks assigned to its Delegate. When nested
48 // however a kDefault RunLoop will only process system tasks while a
49 // kNestableTasksAllowed RunLoop will continue to process application tasks
52 // This is relevant in the case of recursive RunLoops. Some unwanted run loops
53 // may occur when using common controls or printer functions. By default,
54 // recursive task processing is disabled.
56 // In general, nestable RunLoops are to be avoided. They are dangerous and
57 // difficult to get right, so please use with extreme caution.
59 // A specific example where this makes a difference is:
60 // - The thread is running a RunLoop.
61 // - It receives a task #1 and executes it.
62 // - The task #1 implicitly starts a RunLoop, like a MessageBox in the unit
63 // test. This can also be StartDoc or GetSaveFileName.
64 // - The thread receives a task #2 before or while in this second RunLoop.
65 // - With a kNestableTasksAllowed RunLoop, the task #2 will run right away.
66 // Otherwise, it will get executed right after task #1 completes in the main
70 kNestableTasksAllowed,
73 RunLoop(Type type = Type::kDefault);
76 // Run the current RunLoop::Delegate. This blocks until Quit is called. Before
77 // calling Run, be sure to grab the QuitClosure in order to stop the
78 // RunLoop::Delegate asynchronously.
81 // Run the current RunLoop::Delegate until it doesn't find any tasks or
82 // messages in its queue (it goes idle). WARNING: This may never return! Only
83 // use this when repeating tasks such as animated web pages have been shut
87 bool running() const {
88 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
92 // Quit() quits an earlier call to Run() immediately. QuitWhenIdle() quits an
93 // earlier call to Run() when there aren't any tasks or messages in the queue.
95 // These methods are thread-safe but note that Quit() is best-effort when
96 // called from another thread (will quit soon but tasks that were already
97 // queued on this RunLoop will get to run first).
99 // There can be other nested RunLoops servicing the same task queue. Quitting
100 // one RunLoop has no bearing on the others. Quit() and QuitWhenIdle() can be
101 // called before, during or after Run(). If called before Run(), Run() will
102 // return immediately when called. Calling Quit() or QuitWhenIdle() after the
103 // RunLoop has already finished running has no effect.
105 // WARNING: You must NEVER assume that a call to Quit() or QuitWhenIdle() will
106 // terminate the targetted message loop. If a nested RunLoop continues
107 // running, the target may NEVER terminate. It is very easy to livelock (run
108 // forever) in such a case.
112 // Convenience methods to get a closure that safely calls Quit() or
113 // QuitWhenIdle() (has no effect if the RunLoop instance is gone).
115 // The resulting Closure is thread-safe (note however that invoking the
116 // QuitClosure() from another thread than this RunLoop's will result in an
117 // asynchronous rather than immediate Quit()).
121 // PostTask(run_loop.QuitClosure());
123 base::Closure QuitClosure();
124 base::Closure QuitWhenIdleClosure();
126 // Returns true if there is an active RunLoop on this thread.
127 // Safe to call before RegisterDelegateForCurrentThread().
128 static bool IsRunningOnCurrentThread();
130 // Returns true if there is an active RunLoop on this thread and it's nested
131 // within another active RunLoop.
132 // Safe to call before RegisterDelegateForCurrentThread().
133 static bool IsNestedOnCurrentThread();
135 // A NestingObserver is notified when a nested RunLoop begins and ends.
136 class BASE_EXPORT NestingObserver {
138 // Notified before a nested loop starts running work on the current thread.
139 virtual void OnBeginNestedRunLoop() = 0;
140 // Notified after a nested loop is done running work on the current thread.
141 virtual void OnExitNestedRunLoop() {}
144 virtual ~NestingObserver() = default;
147 static void AddNestingObserverOnCurrentThread(NestingObserver* observer);
148 static void RemoveNestingObserverOnCurrentThread(NestingObserver* observer);
150 // A RunLoop::Delegate is a generic interface that allows RunLoop to be
151 // separate from the underlying implementation of the message loop for this
152 // thread. It holds private state used by RunLoops on its associated thread.
153 // One and only one RunLoop::Delegate must be registered on a given thread
154 // via RunLoop::RegisterDelegateForCurrentThread() before RunLoop instances
155 // and RunLoop static methods can be used on it.
156 class BASE_EXPORT Delegate {
161 // Used by RunLoop to inform its Delegate to Run/Quit. Implementations are
162 // expected to keep on running synchronously from the Run() call until the
163 // eventual matching Quit() call. Upon receiving a Quit() call it should
164 // return from the Run() call as soon as possible without executing
165 // remaining tasks/messages. Run() calls can nest in which case each Quit()
166 // call should result in the topmost active Run() call returning. The only
167 // other trigger for Run() to return is the
168 // |should_quit_when_idle_callback_| which the Delegate should probe before
169 // sleeping when it becomes idle. |application_tasks_allowed| is true if
170 // this is the first Run() call on the stack or it was made from a nested
171 // RunLoop of Type::kNestableTasksAllowed (otherwise this Run() level should
172 // only process system tasks).
173 virtual void Run(bool application_tasks_allowed) = 0;
174 virtual void Quit() = 0;
176 // Invoked right before a RunLoop enters a nested Run() call on this
177 // Delegate iff this RunLoop is of type kNestableTasksAllowed. The Delegate
178 // should ensure that the upcoming Run() call will result in processing
179 // application tasks queued ahead of it without further probing. e.g.
180 // message pumps on some platforms, like Mac, need an explicit request to
181 // process application tasks when nested, otherwise they'll only wait for
183 virtual void EnsureWorkScheduled() = 0;
186 // Returns the result of this Delegate's |should_quit_when_idle_callback_|.
187 // "protected" so it can be invoked only by the Delegate itself.
188 bool ShouldQuitWhenIdle();
191 // While the state is owned by the Delegate subclass, only RunLoop can use
193 friend class RunLoop;
195 // A vector-based stack is more memory efficient than the default
196 // deque-based stack as the active RunLoop stack isn't expected to ever
197 // have more than a few entries.
198 using RunLoopStack = base::stack<RunLoop*, std::vector<RunLoop*>>;
200 RunLoopStack active_run_loops_;
201 ObserverList<RunLoop::NestingObserver> nesting_observers_;
204 bool allow_running_for_testing_ = true;
207 // True once this Delegate is bound to a thread via
208 // RegisterDelegateForCurrentThread().
211 // Thread-affine per its use of TLS.
212 THREAD_CHECKER(bound_thread_checker_);
214 DISALLOW_COPY_AND_ASSIGN(Delegate);
217 // Registers |delegate| on the current thread. Must be called once and only
218 // once per thread before using RunLoop methods on it. |delegate| is from then
219 // on forever bound to that thread (including its destruction).
220 static void RegisterDelegateForCurrentThread(Delegate* delegate);
222 // Quits the active RunLoop (when idle) -- there must be one. These were
223 // introduced as prefered temporary replacements to the long deprecated
224 // MessageLoop::Quit(WhenIdle)(Closure) methods. Callers should properly plumb
225 // a reference to the appropriate RunLoop instance (or its QuitClosure)
226 // instead of using these in order to link Run()/Quit() to a single RunLoop
227 // instance and increase readability.
228 static void QuitCurrentDeprecated();
229 static void QuitCurrentWhenIdleDeprecated();
230 static Closure QuitCurrentWhenIdleClosureDeprecated();
232 // Run() will DCHECK if called while there's a ScopedDisallowRunningForTesting
233 // in scope on its thread. This is useful to add safety to some test
234 // constructs which allow multiple task runners to share the main thread in
235 // unit tests. While the main thread can be shared by multiple runners to
236 // deterministically fake multi threading, there can still only be a single
237 // RunLoop::Delegate per thread and RunLoop::Run() should only be invoked from
238 // it (or it would result in incorrectly driving TaskRunner A while in
239 // TaskRunner B's context).
240 class BASE_EXPORT ScopedDisallowRunningForTesting {
242 ScopedDisallowRunningForTesting();
243 ~ScopedDisallowRunningForTesting();
247 Delegate* current_delegate_;
248 const bool previous_run_allowance_;
249 #endif // DCHECK_IS_ON()
251 DISALLOW_COPY_AND_ASSIGN(ScopedDisallowRunningForTesting);
255 FRIEND_TEST_ALL_PREFIXES(MessageLoopTypedTest, RunLoopQuitOrderAfter);
257 #if defined(OS_ANDROID)
258 // Android doesn't support the blocking RunLoop::Run, so it calls
259 // BeforeRun and AfterRun directly.
260 friend class base::MessagePumpForUI;
264 // EFL doesn't support the blocking RunLoop::Run, so it calls
265 // BeforeRun directly.
266 friend class base::MessagePumpForUIEfl;
270 // iOS doesn't support the blocking RunLoop::Run, so it calls
271 // BeforeRun directly.
272 friend class base::MessagePumpUIApplication;
275 // Return false to abort the Run.
279 // A copy of RunLoop::Delegate for the thread driven by tis RunLoop for quick
280 // access without using TLS (also allows access to state from another sequence
281 // during Run(), ref. |sequence_checker_| below).
287 bool run_called_ = false;
290 bool quit_called_ = false;
291 bool running_ = false;
292 // Used to record that QuitWhenIdle() was called on this RunLoop, meaning that
293 // the Delegate should quit Run() once it becomes idle (it's responsible for
294 // probing this state via ShouldQuitWhenIdle()). This state is stored here
295 // rather than pushed to Delegate to support nested RunLoops.
296 bool quit_when_idle_received_ = false;
298 // True if use of QuitCurrent*Deprecated() is allowed. Taking a Quit*Closure()
299 // from a RunLoop implicitly sets this to false, so QuitCurrent*Deprecated()
300 // cannot be used while that RunLoop is being Run().
301 bool allow_quit_current_deprecated_ = true;
303 // RunLoop is not thread-safe. Its state/methods, unless marked as such, may
304 // not be accessed from any other sequence than the thread it was constructed
305 // on. Exception: RunLoop can be safely accessed from one other sequence (or
306 // single parallel task) during Run() -- e.g. to Quit() without having to
307 // plumb ThreatTaskRunnerHandle::Get() throughout a test to repost QuitClosure
309 SEQUENCE_CHECKER(sequence_checker_);
311 const scoped_refptr<SingleThreadTaskRunner> origin_task_runner_;
313 // WeakPtrFactory for QuitClosure safety.
314 base::WeakPtrFactory<RunLoop> weak_factory_;
316 DISALLOW_COPY_AND_ASSIGN(RunLoop);
321 #endif // BASE_RUN_LOOP_H_