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