blob: d135ee7e404b3d8d13ae93da373433b59cfc1a6e [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
[email protected]8e937c1e2012-06-28 22:57:302// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/run_loop.h"
6
Wezd9e4cb772019-01-09 03:07:037#include "base/cancelable_callback.h"
Gabriel Charette2a53350172021-05-06 20:22:558#include "base/check.h"
Peter Kasting960e2d32023-03-14 17:18:419#include "base/compiler_specific.h"
Avi Drissman63e1f992023-01-13 18:54:4310#include "base/functional/bind.h"
11#include "base/functional/callback.h"
David Sanders97aac0de2022-02-07 14:33:5312#include "base/observer_list.h"
Patrick Monette643cdf62021-10-15 19:13:4213#include "base/task/single_thread_task_runner.h"
Etienne Pierre-dorayfc7952f02025-06-06 00:04:3314#include "base/trace_event/trace_event.h"
avi9b6f42932015-12-26 22:15:1415#include "build/build_config.h"
[email protected]8e937c1e2012-06-28 22:57:3016
17namespace base {
18
gab7af9dc02017-05-05 13:38:5419namespace {
20
Peter Kasting4b18d0c2024-09-18 00:56:1121constinit thread_local RunLoop::Delegate* delegate = nullptr;
22constinit thread_local const RunLoop::RunLoopTimeout* run_loop_timeout =
Peter Kasting960e2d32023-03-14 17:18:4123 nullptr;
gab7af9dc02017-05-05 13:38:5424
gabcf5e4ce2017-05-19 22:56:5725// Runs |closure| immediately if this is called on |task_runner|, otherwise
26// forwards |closure| to it.
27void 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
danakje125e8d62021-01-21 22:06:3136void OnRunLoopTimeout(RunLoop* run_loop,
37 const Location& location,
38 OnceCallback<void(const Location&)> on_timeout) {
Wezd9e4cb772019-01-09 03:07:0339 run_loop->Quit();
danakje125e8d62021-01-21 22:06:3140 std::move(on_timeout).Run(location);
Wezd9e4cb772019-01-09 03:07:0341}
42
gab7af9dc02017-05-05 13:38:5443} // namespace
44
Gabriel Charette50518fc2018-05-22 17:53:2245RunLoop::Delegate::Delegate() {
gab273551962017-05-18 06:01:1046 // The Delegate can be created on another thread. It is only bound in
47 // RegisterDelegateForCurrentThread().
48 DETACH_FROM_THREAD(bound_thread_checker_);
49}
50
51RunLoop::Delegate::~Delegate() {
52 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
Gabriel Charetteb87279d2019-06-27 03:21:0453 DCHECK(active_run_loops_.empty());
gab273551962017-05-18 06:01:1054 // A RunLoop::Delegate may be destroyed before it is bound, if so it may still
55 // be on its creation thread (e.g. a Thread that fails to start) and
56 // shouldn't disrupt that thread's state.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4557 if (bound_) {
Peter Kasting960e2d32023-03-14 17:18:4158 DCHECK_EQ(this, delegate);
59 delegate = nullptr;
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4560 }
gab273551962017-05-18 06:01:1061}
62
Gabriel Charettea3ec9612017-12-14 17:22:4063bool RunLoop::Delegate::ShouldQuitWhenIdle() {
Ali Hijazie63cbaf62023-12-20 19:29:3564 const auto* top_loop = active_run_loops_.top().get();
Gabriel Charette2a53350172021-05-06 20:22:5565 if (top_loop->quit_when_idle_) {
Bruce Dawson9066bfa2021-10-14 06:17:2766 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop_ExitedOnIdle",
67 TRACE_ID_LOCAL(top_loop), TRACE_EVENT_FLAG_FLOW_IN);
Gabriel Charettefbf3c622020-11-19 14:51:1368 return true;
69 }
70 return false;
gab273551962017-05-18 06:01:1071}
72
Gabriel Charette0592c3a2017-07-26 12:02:0473// static
Peter Kasting960e2d32023-03-14 17:18:4174void RunLoop::RegisterDelegateForCurrentThread(Delegate* new_delegate) {
gab273551962017-05-18 06:01:1075 // Bind |delegate| to this thread.
Peter Kasting960e2d32023-03-14 17:18:4176 DCHECK(!new_delegate->bound_);
77 DCHECK_CALLED_ON_VALID_THREAD(new_delegate->bound_thread_checker_);
gab273551962017-05-18 06:01:1078
79 // There can only be one RunLoop::Delegate per thread.
Peter Kasting960e2d32023-03-14 17:18:4180 DCHECK(!delegate)
Gabriel Charettefa5e7f0d2018-01-29 12:08:2181 << "Error: Multiple RunLoop::Delegates registered on the same thread.\n\n"
82 "Hint: You perhaps instantiated a second "
Gabriel Charette694c3c332019-08-19 14:53:0583 "MessageLoop/TaskEnvironment on a thread that already had one?";
Peter Kasting960e2d32023-03-14 17:18:4184 delegate = new_delegate;
gab273551962017-05-18 06:01:1085 delegate->bound_ = true;
gab273551962017-05-18 06:01:1086}
87
Gabriel Charette3ff403e2017-08-07 04:22:4888RunLoop::RunLoop(Type type)
Peter Kasting960e2d32023-03-14 17:18:4189 : delegate_(delegate),
Gabriel Charette3ff403e2017-08-07 04:22:4890 type_(type),
Sean Maher7d0e8052022-12-09 01:46:3291 origin_task_runner_(SingleThreadTaskRunner::GetCurrentDefault()) {
Gabriel Charettee2b632b2017-08-02 03:52:1692 DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior "
93 "to using RunLoop.";
gabcf5e4ce2017-05-19 22:56:5794 DCHECK(origin_task_runner_);
[email protected]8e937c1e2012-06-28 22:57:3095}
96
[email protected]8e937c1e2012-06-28 22:57:3097RunLoop::~RunLoop() {
Gabriel Charette78fd3352019-08-01 23:24:1598 // ~RunLoop() must happen-after the RunLoop is done running but it doesn't
99 // have to be on |sequence_checker_| (it usually is but sometimes it can be a
100 // member of a RefCountedThreadSafe object and be destroyed on another thread
101 // after being quit).
102 DCHECK(!running_);
[email protected]8e937c1e2012-06-28 22:57:30103}
104
danakje125e8d62021-01-21 22:06:31105void RunLoop::Run(const Location& location) {
gab980a52712017-05-18 16:20:16106 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
Alexander Timin26ac38f2021-10-05 00:50:36107 // "test" tracing category is used here because in regular scenarios RunLoop
108 // trace events are not useful (each process normally has one RunLoop covering
109 // its entire lifetime) and might be confusing (they make idle processes look
110 // non-idle). In tests, however, creating a RunLoop is a frequent and an
111 // explicit action making this trace event very useful.
112 TRACE_EVENT("test", "RunLoop::Run", "location", location);
gab7af9dc02017-05-05 13:38:54113
Peter Kasting134ef9af2024-12-28 02:30:09114 if (!BeforeRun()) {
[email protected]8e937c1e2012-06-28 22:57:30115 return;
Peter Kasting134ef9af2024-12-28 02:30:09116 }
vadimt12f0f7d2014-09-15 19:19:38117
Wez9d5dd282020-02-10 17:21:22118 // If there is a RunLoopTimeout active then set the timeout.
Alison Gale59c007a2024-04-20 03:05:40119 // TODO(crbug.com/40602467): Use real-time for Run() timeouts so that they
Wezd9e4cb772019-01-09 03:07:03120 // can be applied even in tests which mock TimeTicks::Now().
121 CancelableOnceClosure cancelable_timeout;
Wez9d5dd282020-02-10 17:21:22122 const RunLoopTimeout* run_timeout = GetTimeoutForCurrentThread();
Wezbbffcc52019-02-21 02:01:20123 if (run_timeout) {
danakje125e8d62021-01-21 22:06:31124 cancelable_timeout.Reset(BindOnce(&OnRunLoopTimeout, Unretained(this),
125 location, run_timeout->on_timeout));
Wez9d5dd282020-02-10 17:21:22126 origin_task_runner_->PostDelayedTask(
127 FROM_HERE, cancelable_timeout.callback(), run_timeout->timeout);
Wezd9e4cb772019-01-09 03:07:03128 }
129
Gabriel Charetteb030a4a2017-10-26 01:04:40130 DCHECK_EQ(this, delegate_->active_run_loops_.top());
131 const bool application_tasks_allowed =
132 delegate_->active_run_loops_.size() == 1U ||
133 type_ == Type::kNestableTasksAllowed;
Alex Clarkecfde7b32019-08-15 17:11:47134 delegate_->Run(application_tasks_allowed, TimeDelta::Max());
vadimt12f0f7d2014-09-15 19:19:38135
[email protected]8e937c1e2012-06-28 22:57:30136 AfterRun();
137}
138
139void RunLoop::RunUntilIdle() {
gab980a52712017-05-18 16:20:16140 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gab7af9dc02017-05-05 13:38:54141
Gabriel Charette2a53350172021-05-06 20:22:55142 quit_when_idle_ = true;
[email protected]8e937c1e2012-06-28 22:57:30143 Run();
Gabriel Charette2a53350172021-05-06 20:22:55144
145 if (!AnyQuitCalled()) {
146 quit_when_idle_ = false;
147#if DCHECK_IS_ON()
148 run_allowed_ = true;
149#endif
150 }
[email protected]8e937c1e2012-06-28 22:57:30151}
152
153void RunLoop::Quit() {
gabcf5e4ce2017-05-19 22:56:57154 // Thread-safe.
155
Gabriel Charette3a2ce022020-05-28 19:44:35156 // This can only be hit if RunLoop::Quit() is called directly (QuitClosure()
gabcf5e4ce2017-05-19 22:56:57157 // proxies through ProxyToTaskRunner() as it can only deref its WeakPtr on
158 // |origin_task_runner_|).
159 if (!origin_task_runner_->RunsTasksInCurrentSequence()) {
Wezd9e4cb772019-01-09 03:07:03160 origin_task_runner_->PostTask(FROM_HERE,
161 BindOnce(&RunLoop::Quit, Unretained(this)));
gabcf5e4ce2017-05-19 22:56:57162 return;
163 }
gab7af9dc02017-05-05 13:38:54164
Bruce Dawson9066bfa2021-10-14 06:17:27165 // While Quit() is an "OUT" call to reach one of the quit-states ("IN"),
166 // OUT|IN is used to visually link multiple Quit*() together which can help
167 // when debugging flaky tests.
168 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop::Quit", TRACE_ID_LOCAL(this),
169 TRACE_EVENT_FLAG_FLOW_OUT | TRACE_EVENT_FLAG_FLOW_IN);
Gabriel Charettefbf3c622020-11-19 14:51:13170
[email protected]8e937c1e2012-06-28 22:57:30171 quit_called_ = true;
gab273551962017-05-18 06:01:10172 if (running_ && delegate_->active_run_loops_.top() == this) {
[email protected]8e937c1e2012-06-28 22:57:30173 // This is the inner-most RunLoop, so quit now.
gab273551962017-05-18 06:01:10174 delegate_->Quit();
[email protected]8e937c1e2012-06-28 22:57:30175 }
176}
177
fdoraya4f28ec2016-06-10 00:08:58178void RunLoop::QuitWhenIdle() {
gabcf5e4ce2017-05-19 22:56:57179 // Thread-safe.
180
Gabriel Charette3a2ce022020-05-28 19:44:35181 // This can only be hit if RunLoop::QuitWhenIdle() is called directly
gabcf5e4ce2017-05-19 22:56:57182 // (QuitWhenIdleClosure() proxies through ProxyToTaskRunner() as it can only
183 // deref its WeakPtr on |origin_task_runner_|).
184 if (!origin_task_runner_->RunsTasksInCurrentSequence()) {
185 origin_task_runner_->PostTask(
Wezd9e4cb772019-01-09 03:07:03186 FROM_HERE, BindOnce(&RunLoop::QuitWhenIdle, Unretained(this)));
gabcf5e4ce2017-05-19 22:56:57187 return;
188 }
189
Bruce Dawson9066bfa2021-10-14 06:17:27190 // OUT|IN as in Quit() to link all Quit*() together should there be multiple.
191 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop::QuitWhenIdle",
192 TRACE_ID_LOCAL(this),
193 TRACE_EVENT_FLAG_FLOW_OUT | TRACE_EVENT_FLAG_FLOW_IN);
Gabriel Charettefbf3c622020-11-19 14:51:13194
Gabriel Charette2a53350172021-05-06 20:22:55195 quit_when_idle_ = true;
196 quit_when_idle_called_ = true;
fdoraya4f28ec2016-06-10 00:08:58197}
198
Peter Kasting0bc6a682024-09-09 09:38:34199RepeatingClosure RunLoop::QuitClosure() & {
Gabriel Charette3a2ce022020-05-28 19:44:35200 // Obtaining the QuitClosure() is not thread-safe; either obtain the
201 // QuitClosure() from the owning thread before Run() or invoke Quit() directly
202 // (which is thread-safe).
Gabriel Charetted913e5b2019-06-27 05:41:59203 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gabcf5e4ce2017-05-19 22:56:57204
kylechar650caf02019-07-17 03:25:41205 return BindRepeating(
206 &ProxyToTaskRunner, origin_task_runner_,
207 BindRepeating(&RunLoop::Quit, weak_factory_.GetWeakPtr()));
[email protected]8e937c1e2012-06-28 22:57:30208}
209
Peter Kasting0bc6a682024-09-09 09:38:34210RepeatingClosure RunLoop::QuitWhenIdleClosure() & {
Gabriel Charette3a2ce022020-05-28 19:44:35211 // Obtaining the QuitWhenIdleClosure() is not thread-safe; either obtain the
212 // QuitWhenIdleClosure() from the owning thread before Run() or invoke
213 // QuitWhenIdle() directly (which is thread-safe).
Gabriel Charetted913e5b2019-06-27 05:41:59214 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gabcf5e4ce2017-05-19 22:56:57215
kylechar650caf02019-07-17 03:25:41216 return BindRepeating(
217 &ProxyToTaskRunner, origin_task_runner_,
218 BindRepeating(&RunLoop::QuitWhenIdle, weak_factory_.GetWeakPtr()));
fdoraya3658602016-06-10 18:23:15219}
220
Gabriel Charette2a53350172021-05-06 20:22:55221bool RunLoop::AnyQuitCalled() {
222 return quit_called_ || quit_when_idle_called_;
223}
224
gab7af9dc02017-05-05 13:38:54225// static
gab7af9dc02017-05-05 13:38:54226bool RunLoop::IsRunningOnCurrentThread() {
gab273551962017-05-18 06:01:10227 return delegate && !delegate->active_run_loops_.empty();
gab7af9dc02017-05-05 13:38:54228}
229
230// static
231bool RunLoop::IsNestedOnCurrentThread() {
gab273551962017-05-18 06:01:10232 return delegate && delegate->active_run_loops_.size() > 1;
gab7af9dc02017-05-05 13:38:54233}
234
235// static
236void RunLoop::AddNestingObserverOnCurrentThread(NestingObserver* observer) {
gab273551962017-05-18 06:01:10237 DCHECK(delegate);
gab273551962017-05-18 06:01:10238 delegate->nesting_observers_.AddObserver(observer);
gab7af9dc02017-05-05 13:38:54239}
240
241// static
242void RunLoop::RemoveNestingObserverOnCurrentThread(NestingObserver* observer) {
gab273551962017-05-18 06:01:10243 DCHECK(delegate);
gab273551962017-05-18 06:01:10244 delegate->nesting_observers_.RemoveObserver(observer);
gab7af9dc02017-05-05 13:38:54245}
246
Gabriel Charettea44975052017-08-21 23:14:04247#if DCHECK_IS_ON()
Hans Wennborg9b292ba2022-02-15 16:01:29248ScopedDisallowRunningRunLoop::ScopedDisallowRunningRunLoop()
Peter Kasting960e2d32023-03-14 17:18:41249 : current_delegate_(delegate),
250 previous_run_allowance_(current_delegate_ &&
251 current_delegate_->allow_running_for_testing_) {
Peter Kasting134ef9af2024-12-28 02:30:09252 if (current_delegate_) {
Gabriel Charettea44975052017-08-21 23:14:04253 current_delegate_->allow_running_for_testing_ = false;
Peter Kasting134ef9af2024-12-28 02:30:09254 }
Gabriel Charettea44975052017-08-21 23:14:04255}
256
Hans Wennborg9b292ba2022-02-15 16:01:29257ScopedDisallowRunningRunLoop::~ScopedDisallowRunningRunLoop() {
Peter Kasting960e2d32023-03-14 17:18:41258 DCHECK_EQ(current_delegate_, delegate);
Peter Kasting134ef9af2024-12-28 02:30:09259 if (current_delegate_) {
Gabriel Charettea44975052017-08-21 23:14:04260 current_delegate_->allow_running_for_testing_ = previous_run_allowance_;
Peter Kasting134ef9af2024-12-28 02:30:09261 }
Gabriel Charettea44975052017-08-21 23:14:04262}
263#else // DCHECK_IS_ON()
264// Defined out of line so that the compiler doesn't inline these and realize
265// the scope has no effect and then throws an "unused variable" warning in
266// non-dcheck builds.
Hans Wennborg9b292ba2022-02-15 16:01:29267ScopedDisallowRunningRunLoop::ScopedDisallowRunningRunLoop() = default;
268ScopedDisallowRunningRunLoop::~ScopedDisallowRunningRunLoop() = default;
Gabriel Charettea44975052017-08-21 23:14:04269#endif // DCHECK_IS_ON()
270
Wez9d5dd282020-02-10 17:21:22271RunLoop::RunLoopTimeout::RunLoopTimeout() = default;
272
273RunLoop::RunLoopTimeout::~RunLoopTimeout() = default;
274
275// static
276void RunLoop::SetTimeoutForCurrentThread(const RunLoopTimeout* timeout) {
Peter Kasting960e2d32023-03-14 17:18:41277 run_loop_timeout = timeout;
Wez9d5dd282020-02-10 17:21:22278}
279
280// static
281const RunLoop::RunLoopTimeout* RunLoop::GetTimeoutForCurrentThread() {
Peter Kasting960e2d32023-03-14 17:18:41282 // Workaround false-positive MSAN use-of-uninitialized-value on
283 // thread_local storage for loaded libraries:
284 // https://github.com/google/sanitizers/issues/1265
285 MSAN_UNPOISON(&run_loop_timeout, sizeof(RunLoopTimeout*));
286
287 return run_loop_timeout;
Wez212eeb72020-02-04 17:54:54288}
289
[email protected]8e937c1e2012-06-28 22:57:30290bool RunLoop::BeforeRun() {
gab980a52712017-05-18 16:20:16291 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gab7af9dc02017-05-05 13:38:54292
gabcf5e4ce2017-05-19 22:56:57293#if DCHECK_IS_ON()
Gabriel Charettea44975052017-08-21 23:14:04294 DCHECK(delegate_->allow_running_for_testing_)
295 << "RunLoop::Run() isn't allowed in the scope of a "
Hans Wennborg9b292ba2022-02-15 16:01:29296 "ScopedDisallowRunningRunLoop. Hint: if mixing "
Gabriel Charettea44975052017-08-21 23:14:04297 "TestMockTimeTaskRunners on same thread, use TestMockTimeTaskRunner's "
298 "API instead of RunLoop to drive individual task runners.";
Gabriel Charette2a53350172021-05-06 20:22:55299 DCHECK(run_allowed_);
300 run_allowed_ = false;
gabcf5e4ce2017-05-19 22:56:57301#endif // DCHECK_IS_ON()
[email protected]8e937c1e2012-06-28 22:57:30302
303 // Allow Quit to be called before Run.
Gabriel Charettefbf3c622020-11-19 14:51:13304 if (quit_called_) {
Bruce Dawson9066bfa2021-10-14 06:17:27305 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop_ExitedEarly",
306 TRACE_ID_LOCAL(this), TRACE_EVENT_FLAG_FLOW_IN);
[email protected]8e937c1e2012-06-28 22:57:30307 return false;
Gabriel Charettefbf3c622020-11-19 14:51:13308 }
[email protected]8e937c1e2012-06-28 22:57:30309
Gabriel Charetteb87279d2019-06-27 03:21:04310 auto& active_run_loops = delegate_->active_run_loops_;
311 active_run_loops.push(this);
[email protected]8e937c1e2012-06-28 22:57:30312
Gabriel Charetteb87279d2019-06-27 03:21:04313 const bool is_nested = active_run_loops.size() > 1;
gab7af9dc02017-05-05 13:38:54314
315 if (is_nested) {
Peter Kasting134ef9af2024-12-28 02:30:09316 for (auto& observer : delegate_->nesting_observers_) {
gab7af9dc02017-05-05 13:38:54317 observer.OnBeginNestedRunLoop();
Peter Kasting134ef9af2024-12-28 02:30:09318 }
319 if (type_ == Type::kNestableTasksAllowed) {
Gabriel Charette3ff403e2017-08-07 04:22:48320 delegate_->EnsureWorkScheduled();
Peter Kasting134ef9af2024-12-28 02:30:09321 }
gab7af9dc02017-05-05 13:38:54322 }
jamescookaacdfd02016-04-28 00:50:03323
[email protected]8e937c1e2012-06-28 22:57:30324 running_ = true;
325 return true;
326}
327
328void RunLoop::AfterRun() {
gab980a52712017-05-18 16:20:16329 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gab7af9dc02017-05-05 13:38:54330
[email protected]8e937c1e2012-06-28 22:57:30331 running_ = false;
332
Bruce Dawson9066bfa2021-10-14 06:17:27333 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop_Exited",
334 TRACE_ID_LOCAL(this), TRACE_EVENT_FLAG_FLOW_IN);
Gabriel Charettefbf3c622020-11-19 14:51:13335
Gabriel Charetteb87279d2019-06-27 03:21:04336 auto& active_run_loops = delegate_->active_run_loops_;
337 DCHECK_EQ(active_run_loops.top(), this);
338 active_run_loops.pop();
gab7af9dc02017-05-05 13:38:54339
Gabriel Charetteb87279d2019-06-27 03:21:04340 // Exiting a nested RunLoop?
341 if (!active_run_loops.empty()) {
Peter Kasting134ef9af2024-12-28 02:30:09342 for (auto& observer : delegate_->nesting_observers_) {
Francois Doray80bdddf2018-01-04 16:17:32343 observer.OnExitNestedRunLoop();
Peter Kasting134ef9af2024-12-28 02:30:09344 }
Francois Doray80bdddf2018-01-04 16:17:32345
Gabriel Charetteb87279d2019-06-27 03:21:04346 // Execute deferred Quit, if any:
Peter Kasting134ef9af2024-12-28 02:30:09347 if (active_run_loops.top()->quit_called_) {
Gabriel Charetteb87279d2019-06-27 03:21:04348 delegate_->Quit();
Peter Kasting134ef9af2024-12-28 02:30:09349 }
Gabriel Charetteb87279d2019-06-27 03:21:04350 }
[email protected]8e937c1e2012-06-28 22:57:30351}
352
353} // namespace base