| 6 |
| 7 | #include "base/bind.h" |
| 8 | #include "base/callback.h" |
| 9 | #include "base/cancelable_callback.h" |
| 10 | #include "base/no_destructor.h" |
| 11 | #include "base/single_thread_task_runner.h" |
| 12 | #include "base/threading/thread_local.h" |
| 13 | #include "base/threading/thread_task_runner_handle.h" |
| 14 | #include "build/build_config.h" |
| 15 |
| 16 | namespace base { |
| 17 |
| 18 | namespace { |
| 19 |
| 20 | ThreadLocalPointer<RunLoop::Delegate>& GetTlsDelegate() { |
| 21 | static base::NoDestructor<ThreadLocalPointer<RunLoop::Delegate>> instance; |
| 22 | return *instance; |
| 23 | } |
| 24 |
| 25 | // Runs |closure| immediately if this is called on |task_runner|, otherwise |
| 26 | // forwards |closure| to it. |
| 27 | void ProxyToTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner, |
| 28 | OnceClosure closure) { |
| 29 | if (task_runner->RunsTasksInCurrentSequence()) { |
| 30 | std::move(closure).Run(); |
| 31 | return; |
| 32 | } |
| 33 | task_runner->PostTask(FROM_HERE, std::move(closure)); |
| 34 | } |
| 35 |
| 36 | ThreadLocalPointer<const RunLoop::RunLoopTimeout>& RunLoopTimeoutTLS() { |
| 37 | static NoDestructor<ThreadLocalPointer<const RunLoop::RunLoopTimeout>> tls; |
| 38 | return *tls; |
| 39 | } |
| 40 |
| 41 | void OnRunLoopTimeout(RunLoop* run_loop, OnceClosure on_timeout) { |
| 42 | run_loop->Quit(); |
| 43 | std::move(on_timeout).Run(); |
| 44 | } |
| 45 |
| 46 | } // namespace |
| 47 |
| 48 | RunLoop::Delegate::Delegate() { |
| 49 | // The Delegate can be created on another thread. It is only bound in |
| 50 | // RegisterDelegateForCurrentThread(). |
| 51 | DETACH_FROM_THREAD(bound_thread_checker_); |
| 52 | } |
| 53 |
| 54 | RunLoop::Delegate::~Delegate() { |
| 55 | DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_); |
| 56 | DCHECK(active_run_loops_.empty()); |
| 57 | // A RunLoop::Delegate may be destroyed before it is bound, if so it may still |
| 58 | // be on its creation thread (e.g. a Thread that fails to start) and |
| 59 | // shouldn't disrupt that thread's state. |
| 60 | if (bound_) { |
| 61 | DCHECK_EQ(this, GetTlsDelegate().Get()); |
| 62 | GetTlsDelegate().Set(nullptr); |
| 63 | } |
| 64 | } |
| 65 |
| 66 | bool RunLoop::Delegate::ShouldQuitWhenIdle() { |
| 67 | return active_run_loops_.top()->quit_when_idle_received_; |
| 68 | } |
| 69 |
| 70 | // static |
| 71 | void RunLoop::RegisterDelegateForCurrentThread(Delegate* delegate) { |
| 72 | // Bind |delegate| to this thread. |
| 73 | DCHECK(!delegate->bound_); |
| 74 | DCHECK_CALLED_ON_VALID_THREAD(delegate->bound_thread_checker_); |
| 75 |
| 76 | // There can only be one RunLoop::Delegate per thread. |
| 77 | DCHECK(!GetTlsDelegate().Get()) |
| 78 | << "Error: Multiple RunLoop::Delegates registered on the same thread.\n\n" |
| 79 | "Hint: You perhaps instantiated a second " |
| 80 | "MessageLoop/TaskEnvironment on a thread that already had one?"; |
| 81 | GetTlsDelegate().Set(delegate); |
| 82 | delegate->bound_ = true; |
| 83 | } |
| 84 |
| 85 | RunLoop::RunLoop(Type type) |
| 86 | : delegate_(GetTlsDelegate().Get()), |
| 87 | type_(type), |
| 88 | origin_task_runner_(ThreadTaskRunnerHandle::Get()) { |
| 89 | DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior " |
| 90 | "to using RunLoop."; |
| 91 | DCHECK(origin_task_runner_); |
| 92 | } |
| 93 |
| 94 | RunLoop::~RunLoop() { |
| 95 | // ~RunLoop() must happen-after the RunLoop is done running but it doesn't |
| 96 | // have to be on |sequence_checker_| (it usually is but sometimes it can be a |
| 97 | // member of a RefCountedThreadSafe object and be destroyed on another thread |
| 98 | // after being quit). |
| 99 | DCHECK(!running_); |
| 100 | } |
| 101 |
| 102 | void RunLoop::Run() { |
| 103 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
| 104 |
| 105 | if (!BeforeRun()) |
| 106 | return; |
| 107 |
| 108 | // If there is a RunLoopTimeout active then set the timeout. |
| 109 | // TODO(crbug.com/905412): Use real-time for Run() timeouts so that they |
| 110 | // can be applied even in tests which mock TimeTicks::Now(). |
| 111 | CancelableOnceClosure cancelable_timeout; |
| 112 | const RunLoopTimeout* run_timeout = GetTimeoutForCurrentThread(); |
| 113 | if (run_timeout) { |
| 114 | cancelable_timeout.Reset( |
| 115 | BindOnce(&OnRunLoopTimeout, Unretained(this), run_timeout->on_timeout)); |
| 116 | origin_task_runner_->PostDelayedTask( |
| 117 | FROM_HERE, cancelable_timeout.callback(), run_timeout->timeout); |
| 118 | } |
| 119 |
| 120 | DCHECK_EQ(this, delegate_->active_run_loops_.top()); |
| 121 | const bool application_tasks_allowed = |
| 122 | delegate_->active_run_loops_.size() == 1U || |
| 123 | type_ == Type::kNestableTasksAllowed; |
| 124 | delegate_->Run(application_tasks_allowed, TimeDelta::Max()); |
| 125 |
| 126 | AfterRun(); |
| 127 | } |
| 128 |
| 129 | void RunLoop::RunUntilIdle() { |
| 130 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
| 131 |
| 132 | quit_when_idle_received_ = true; |
| 133 | Run(); |
| 134 | } |
| 135 |
| 136 | void RunLoop::Quit() { |
| 137 | // Thread-safe. |
| 138 |
| 139 | // This can only be hit if run_loop->Quit() is called directly (QuitClosure() |
| 140 | // proxies through ProxyToTaskRunner() as it can only deref its WeakPtr on |
| 141 | // |origin_task_runner_|). |
| 142 | if (!origin_task_runner_->RunsTasksInCurrentSequence()) { |
| 143 | origin_task_runner_->PostTask(FROM_HERE, |
| 144 | BindOnce(&RunLoop::Quit, Unretained(this))); |
| 145 | return; |
| 146 | } |
| 147 |
| 148 | quit_called_ = true; |
| 149 | if (running_ && delegate_->active_run_loops_.top() == this) { |
| 150 | // This is the inner-most RunLoop, so quit now. |
| 151 | delegate_->Quit(); |
| 152 | } |
| 153 | } |
| 154 |
| 155 | void RunLoop::QuitWhenIdle() { |
| 156 | // Thread-safe. |
| 157 |
| 158 | // This can only be hit if run_loop->QuitWhenIdle() is called directly |
| 159 | // (QuitWhenIdleClosure() proxies through ProxyToTaskRunner() as it can only |
| 160 | // deref its WeakPtr on |origin_task_runner_|). |
| 161 | if (!origin_task_runner_->RunsTasksInCurrentSequence()) { |
| 162 | origin_task_runner_->PostTask( |
| 163 | FROM_HERE, BindOnce(&RunLoop::QuitWhenIdle, Unretained(this))); |
| 164 | return; |
| 165 | } |
| 166 |
| 167 | quit_when_idle_received_ = true; |
| 168 | } |
| 169 |
| 170 | RepeatingClosure RunLoop::QuitClosure() { |
| 171 | // Obtaining the QuitClosure() is not thread-safe; either post the |
| 172 | // QuitClosure() from the run thread or invoke Quit() directly (which is |
| 173 | // thread-safe). |
| 174 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
| 175 | allow_quit_current_deprecated_ = false; |
| 176 |
| 177 | return BindRepeating( |
| 178 | &ProxyToTaskRunner, origin_task_runner_, |
| 179 | BindRepeating(&RunLoop::Quit, weak_factory_.GetWeakPtr())); |
| 180 | } |
| 181 |
| 182 | RepeatingClosure RunLoop::QuitWhenIdleClosure() { |
| 183 | // Obtaining the QuitWhenIdleClosure() is not thread-safe; either post the |
| 184 | // QuitWhenIdleClosure() from the run thread or invoke QuitWhenIdle() directly |
| 185 | // (which is thread-safe). |
| 186 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
| 187 | allow_quit_current_deprecated_ = false; |
| 188 |
| 189 | return BindRepeating( |
| 190 | &ProxyToTaskRunner, origin_task_runner_, |
| 191 | BindRepeating(&RunLoop::QuitWhenIdle, weak_factory_.GetWeakPtr())); |
| 192 | } |
| 193 |
| 194 | // static |
| 195 | bool RunLoop::IsRunningOnCurrentThread() { |
| 196 | Delegate* delegate = GetTlsDelegate().Get(); |
| 197 | return delegate && !delegate->active_run_loops_.empty(); |
| 198 | } |
| 199 |
| 200 | // static |
| 201 | bool RunLoop::IsNestedOnCurrentThread() { |
| 202 | Delegate* delegate = GetTlsDelegate().Get(); |
| 203 | return delegate && delegate->active_run_loops_.size() > 1; |
| 204 | } |
| 205 |
| 206 | // static |
| 207 | void RunLoop::AddNestingObserverOnCurrentThread(NestingObserver* observer) { |
| 208 | Delegate* delegate = GetTlsDelegate().Get(); |
| 209 | DCHECK(delegate); |
| 210 | delegate->nesting_observers_.AddObserver(observer); |
| 211 | } |
| 212 |
| 213 | // static |
| 214 | void RunLoop::RemoveNestingObserverOnCurrentThread(NestingObserver* observer) { |
| 215 | Delegate* delegate = GetTlsDelegate().Get(); |
| 216 | DCHECK(delegate); |
| 217 | delegate->nesting_observers_.RemoveObserver(observer); |
| 218 | } |
| 219 |
| 220 | // static |
| 221 | void RunLoop::QuitCurrentDeprecated() { |
| 222 | DCHECK(IsRunningOnCurrentThread()); |
| 223 | Delegate* delegate = GetTlsDelegate().Get(); |
| 224 | DCHECK(delegate->active_run_loops_.top()->allow_quit_current_deprecated_) |
| 225 | << "Please migrate off QuitCurrentDeprecated(), e.g. to QuitClosure()."; |
| 226 | delegate->active_run_loops_.top()->Quit(); |
| 227 | } |
| 228 |
| 229 | // static |
| 230 | void RunLoop::QuitCurrentWhenIdleDeprecated() { |
| 231 | DCHECK(IsRunningOnCurrentThread()); |
| 232 | Delegate* delegate = GetTlsDelegate().Get(); |
| 233 | DCHECK(delegate->active_run_loops_.top()->allow_quit_current_deprecated_) |
| 234 | << "Please migrate off QuitCurrentWhenIdleDeprecated(), e.g. to " |
| 235 | "QuitWhenIdleClosure()."; |
| 236 | delegate->active_run_loops_.top()->QuitWhenIdle(); |
| 237 | } |
| 238 |
| 239 | // static |
| 240 | RepeatingClosure RunLoop::QuitCurrentWhenIdleClosureDeprecated() { |
| 241 | // TODO(844016): Fix callsites and enable this check, or remove the API. |
| 242 | // Delegate* delegate = GetTlsDelegate().Get(); |
| 243 | // DCHECK(delegate->active_run_loops_.top()->allow_quit_current_deprecated_) |
| 244 | // << "Please migrate off QuitCurrentWhenIdleClosureDeprecated(), e.g to " |
| 245 | // "QuitWhenIdleClosure()."; |
| 246 | return BindRepeating(&RunLoop::QuitCurrentWhenIdleDeprecated); |
| 247 | } |
| 248 |
| 249 | #if DCHECK_IS_ON() |
| 250 | RunLoop::ScopedDisallowRunningForTesting::ScopedDisallowRunningForTesting() |
| 251 | : current_delegate_(GetTlsDelegate().Get()), |
| 252 | previous_run_allowance_( |
| 253 | current_delegate_ ? current_delegate_->allow_running_for_testing_ |
| 254 | : false) { |
| 255 | if (current_delegate_) |
| 256 | current_delegate_->allow_running_for_testing_ = false; |
| 257 | } |
| 258 |
| 259 | RunLoop::ScopedDisallowRunningForTesting::~ScopedDisallowRunningForTesting() { |
| 260 | DCHECK_EQ(current_delegate_, GetTlsDelegate().Get()); |
| 261 | if (current_delegate_) |
| 262 | current_delegate_->allow_running_for_testing_ = previous_run_allowance_; |
| 263 | } |
| 264 | #else // DCHECK_IS_ON() |
| 265 | // Defined out of line so that the compiler doesn't inline these and realize |
| 266 | // the scope has no effect and then throws an "unused variable" warning in |
| 267 | // non-dcheck builds. |
| 268 | RunLoop::ScopedDisallowRunningForTesting::ScopedDisallowRunningForTesting() = |
| 269 | default; |
| 270 | RunLoop::ScopedDisallowRunningForTesting::~ScopedDisallowRunningForTesting() = |
| 271 | default; |
| 272 | #endif // DCHECK_IS_ON() |
| 273 |
| 274 | RunLoop::RunLoopTimeout::RunLoopTimeout() = default; |
| 275 |
| 276 | RunLoop::RunLoopTimeout::~RunLoopTimeout() = default; |
| 277 |
| 278 | // static |
| 279 | void RunLoop::SetTimeoutForCurrentThread(const RunLoopTimeout* timeout) { |
| 280 | RunLoopTimeoutTLS().Set(timeout); |
| 281 | } |
| 282 |
| 283 | // static |
| 284 | const RunLoop::RunLoopTimeout* RunLoop::GetTimeoutForCurrentThread() { |
| 285 | return RunLoopTimeoutTLS().Get(); |
| 286 | } |
| 287 |
| 288 | bool RunLoop::BeforeRun() { |
| 289 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
| 290 |
| 291 | #if DCHECK_IS_ON() |
| 292 | DCHECK(delegate_->allow_running_for_testing_) |
| 293 | << "RunLoop::Run() isn't allowed in the scope of a " |
| 294 | "ScopedDisallowRunningForTesting. Hint: if mixing " |
| 295 | "TestMockTimeTaskRunners on same thread, use TestMockTimeTaskRunner's " |
| 296 | "API instead of RunLoop to drive individual task runners."; |
| 297 | DCHECK(!run_called_); |
| 298 | run_called_ = true; |
| 299 | #endif // DCHECK_IS_ON() |
| 300 |
| 301 | // Allow Quit to be called before Run. |
| 302 | if (quit_called_) |
| 303 | return false; |
| 304 |
| 305 | auto& active_run_loops = delegate_->active_run_loops_; |
| 306 | active_run_loops.push(this); |
| 307 |
| 308 | const bool is_nested = active_run_loops.size() > 1; |
| 309 |
| 310 | if (is_nested) { |
| 311 | for (auto& observer : delegate_->nesting_observers_) |
| 312 | observer.OnBeginNestedRunLoop(); |
| 313 | if (type_ == Type::kNestableTasksAllowed) |
| 314 | delegate_->EnsureWorkScheduled(); |
| 315 | } |
| 316 |
| 317 | running_ = true; |
| 318 | return true; |
| 319 | } |
| 320 |
| 321 | void RunLoop::AfterRun() { |
| 322 | DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); |
| 323 |
| 324 | running_ = false; |
| 325 |
| 326 | auto& active_run_loops = delegate_->active_run_loops_; |
| 327 | DCHECK_EQ(active_run_loops.top(), this); |
| 328 | active_run_loops.pop(); |
| 329 |
| 330 | // Exiting a nested RunLoop? |
| 331 | if (!active_run_loops.empty()) { |
| 332 | for (auto& observer : delegate_->nesting_observers_) |
| 333 | observer.OnExitNestedRunLoop(); |
| 334 |
| 335 | // Execute deferred Quit, if any: |
| 336 | if (active_run_loops.top()->quit_called_) |
| 337 | delegate_->Quit(); |
| 338 | } |
| 339 | } |
| 340 |
| 341 | } // namespace base |
| 342 |