[go: nahoru, domu]

blob: 72a884ffef613dd43de4d126eb871be68b43c582 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
jbates@chromium.org8e937c1e2012-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"
Gabriel Charettefbf3c622020-11-19 14:51:1314#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1415#include "build/build_config.h"
Peter Kasting960e2d32023-03-14 17:18:4116#include "third_party/abseil-cpp/absl/base/attributes.h"
jbates@chromium.org8e937c1e2012-06-28 22:57:3017
18namespace base {
19
gab7af9dc02017-05-05 13:38:5420namespace {
21
Peter Kasting960e2d32023-03-14 17:18:4122ABSL_CONST_INIT thread_local RunLoop::Delegate* delegate = nullptr;
23ABSL_CONST_INIT thread_local const RunLoop::RunLoopTimeout* run_loop_timeout =
24 nullptr;
gab7af9dc02017-05-05 13:38:5425
gabcf5e4ce2017-05-19 22:56:5726// Runs |closure| immediately if this is called on |task_runner|, otherwise
27// forwards |closure| to it.
28void ProxyToTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner,
29 OnceClosure closure) {
30 if (task_runner->RunsTasksInCurrentSequence()) {
31 std::move(closure).Run();
32 return;
33 }
34 task_runner->PostTask(FROM_HERE, std::move(closure));
35}
36
danakje125e8d62021-01-21 22:06:3137void OnRunLoopTimeout(RunLoop* run_loop,
38 const Location& location,
39 OnceCallback<void(const Location&)> on_timeout) {
Wezd9e4cb772019-01-09 03:07:0340 run_loop->Quit();
danakje125e8d62021-01-21 22:06:3141 std::move(on_timeout).Run(location);
Wezd9e4cb772019-01-09 03:07:0342}
43
gab7af9dc02017-05-05 13:38:5444} // namespace
45
Gabriel Charette50518fc2018-05-22 17:53:2246RunLoop::Delegate::Delegate() {
gab273551962017-05-18 06:01:1047 // The Delegate can be created on another thread. It is only bound in
48 // RegisterDelegateForCurrentThread().
49 DETACH_FROM_THREAD(bound_thread_checker_);
50}
51
52RunLoop::Delegate::~Delegate() {
53 DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
Gabriel Charetteb87279d2019-06-27 03:21:0454 DCHECK(active_run_loops_.empty());
gab273551962017-05-18 06:01:1055 // A RunLoop::Delegate may be destroyed before it is bound, if so it may still
56 // be on its creation thread (e.g. a Thread that fails to start) and
57 // shouldn't disrupt that thread's state.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4558 if (bound_) {
Peter Kasting960e2d32023-03-14 17:18:4159 DCHECK_EQ(this, delegate);
60 delegate = nullptr;
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4561 }
gab273551962017-05-18 06:01:1062}
63
Gabriel Charettea3ec9612017-12-14 17:22:4064bool RunLoop::Delegate::ShouldQuitWhenIdle() {
Ali Hijazie63cbaf62023-12-20 19:29:3565 const auto* top_loop = active_run_loops_.top().get();
Gabriel Charette2a53350172021-05-06 20:22:5566 if (top_loop->quit_when_idle_) {
Bruce Dawson9066bfa2021-10-14 06:17:2767 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop_ExitedOnIdle",
68 TRACE_ID_LOCAL(top_loop), TRACE_EVENT_FLAG_FLOW_IN);
Gabriel Charettefbf3c622020-11-19 14:51:1369 return true;
70 }
71 return false;
gab273551962017-05-18 06:01:1072}
73
Gabriel Charette0592c3a2017-07-26 12:02:0474// static
Peter Kasting960e2d32023-03-14 17:18:4175void RunLoop::RegisterDelegateForCurrentThread(Delegate* new_delegate) {
gab273551962017-05-18 06:01:1076 // Bind |delegate| to this thread.
Peter Kasting960e2d32023-03-14 17:18:4177 DCHECK(!new_delegate->bound_);
78 DCHECK_CALLED_ON_VALID_THREAD(new_delegate->bound_thread_checker_);
gab273551962017-05-18 06:01:1079
80 // There can only be one RunLoop::Delegate per thread.
Peter Kasting960e2d32023-03-14 17:18:4181 DCHECK(!delegate)
Gabriel Charettefa5e7f0d2018-01-29 12:08:2182 << "Error: Multiple RunLoop::Delegates registered on the same thread.\n\n"
83 "Hint: You perhaps instantiated a second "
Gabriel Charette694c3c332019-08-19 14:53:0584 "MessageLoop/TaskEnvironment on a thread that already had one?";
Peter Kasting960e2d32023-03-14 17:18:4185 delegate = new_delegate;
gab273551962017-05-18 06:01:1086 delegate->bound_ = true;
gab273551962017-05-18 06:01:1087}
88
Gabriel Charette3ff403e2017-08-07 04:22:4889RunLoop::RunLoop(Type type)
Peter Kasting960e2d32023-03-14 17:18:4190 : delegate_(delegate),
Gabriel Charette3ff403e2017-08-07 04:22:4891 type_(type),
Sean Maher7d0e8052022-12-09 01:46:3292 origin_task_runner_(SingleThreadTaskRunner::GetCurrentDefault()) {
Gabriel Charettee2b632b2017-08-02 03:52:1693 DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior "
94 "to using RunLoop.";
gabcf5e4ce2017-05-19 22:56:5795 DCHECK(origin_task_runner_);
jbates@chromium.org8e937c1e2012-06-28 22:57:3096}
97
jbates@chromium.org8e937c1e2012-06-28 22:57:3098RunLoop::~RunLoop() {
Gabriel Charette78fd3352019-08-01 23:24:1599 // ~RunLoop() must happen-after the RunLoop is done running but it doesn't
100 // have to be on |sequence_checker_| (it usually is but sometimes it can be a
101 // member of a RefCountedThreadSafe object and be destroyed on another thread
102 // after being quit).
103 DCHECK(!running_);
jbates@chromium.org8e937c1e2012-06-28 22:57:30104}
105
danakje125e8d62021-01-21 22:06:31106void RunLoop::Run(const Location& location) {
gab980a52712017-05-18 16:20:16107 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
Alexander Timin26ac38f2021-10-05 00:50:36108 // "test" tracing category is used here because in regular scenarios RunLoop
109 // trace events are not useful (each process normally has one RunLoop covering
110 // its entire lifetime) and might be confusing (they make idle processes look
111 // non-idle). In tests, however, creating a RunLoop is a frequent and an
112 // explicit action making this trace event very useful.
113 TRACE_EVENT("test", "RunLoop::Run", "location", location);
gab7af9dc02017-05-05 13:38:54114
jbates@chromium.org8e937c1e2012-06-28 22:57:30115 if (!BeforeRun())
116 return;
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
jbates@chromium.org8e937c1e2012-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;
jbates@chromium.org8e937c1e2012-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 }
jbates@chromium.org8e937c1e2012-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
jbates@chromium.org8e937c1e2012-06-28 22:57:30171 quit_called_ = true;
gab273551962017-05-18 06:01:10172 if (running_ && delegate_->active_run_loops_.top() == this) {
jbates@chromium.org8e937c1e2012-06-28 22:57:30173 // This is the inner-most RunLoop, so quit now.
gab273551962017-05-18 06:01:10174 delegate_->Quit();
jbates@chromium.org8e937c1e2012-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
kylechar650caf02019-07-17 03:25:41199RepeatingClosure 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()));
jbates@chromium.org8e937c1e2012-06-28 22:57:30208}
209
kylechar650caf02019-07-17 03:25:41210RepeatingClosure 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 Charette5bc88412018-05-16 03:28:25247
Gabriel Charettea44975052017-08-21 23:14:04248#if DCHECK_IS_ON()
Hans Wennborg9b292ba2022-02-15 16:01:29249ScopedDisallowRunningRunLoop::ScopedDisallowRunningRunLoop()
Peter Kasting960e2d32023-03-14 17:18:41250 : current_delegate_(delegate),
251 previous_run_allowance_(current_delegate_ &&
252 current_delegate_->allow_running_for_testing_) {
Gabriel Charettea44975052017-08-21 23:14:04253 if (current_delegate_)
254 current_delegate_->allow_running_for_testing_ = false;
255}
256
Hans Wennborg9b292ba2022-02-15 16:01:29257ScopedDisallowRunningRunLoop::~ScopedDisallowRunningRunLoop() {
Peter Kasting960e2d32023-03-14 17:18:41258 DCHECK_EQ(current_delegate_, delegate);
Gabriel Charettea44975052017-08-21 23:14:04259 if (current_delegate_)
260 current_delegate_->allow_running_for_testing_ = previous_run_allowance_;
261}
262#else // DCHECK_IS_ON()
263// Defined out of line so that the compiler doesn't inline these and realize
264// the scope has no effect and then throws an "unused variable" warning in
265// non-dcheck builds.
Hans Wennborg9b292ba2022-02-15 16:01:29266ScopedDisallowRunningRunLoop::ScopedDisallowRunningRunLoop() = default;
267ScopedDisallowRunningRunLoop::~ScopedDisallowRunningRunLoop() = default;
Gabriel Charettea44975052017-08-21 23:14:04268#endif // DCHECK_IS_ON()
269
Wez9d5dd282020-02-10 17:21:22270RunLoop::RunLoopTimeout::RunLoopTimeout() = default;
271
272RunLoop::RunLoopTimeout::~RunLoopTimeout() = default;
273
274// static
275void RunLoop::SetTimeoutForCurrentThread(const RunLoopTimeout* timeout) {
Peter Kasting960e2d32023-03-14 17:18:41276 run_loop_timeout = timeout;
Wez9d5dd282020-02-10 17:21:22277}
278
279// static
280const RunLoop::RunLoopTimeout* RunLoop::GetTimeoutForCurrentThread() {
Peter Kasting960e2d32023-03-14 17:18:41281 // Workaround false-positive MSAN use-of-uninitialized-value on
282 // thread_local storage for loaded libraries:
283 // https://github.com/google/sanitizers/issues/1265
284 MSAN_UNPOISON(&run_loop_timeout, sizeof(RunLoopTimeout*));
285
286 return run_loop_timeout;
Wez212eeb72020-02-04 17:54:54287}
288
jbates@chromium.org8e937c1e2012-06-28 22:57:30289bool RunLoop::BeforeRun() {
gab980a52712017-05-18 16:20:16290 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gab7af9dc02017-05-05 13:38:54291
gabcf5e4ce2017-05-19 22:56:57292#if DCHECK_IS_ON()
Gabriel Charettea44975052017-08-21 23:14:04293 DCHECK(delegate_->allow_running_for_testing_)
294 << "RunLoop::Run() isn't allowed in the scope of a "
Hans Wennborg9b292ba2022-02-15 16:01:29295 "ScopedDisallowRunningRunLoop. Hint: if mixing "
Gabriel Charettea44975052017-08-21 23:14:04296 "TestMockTimeTaskRunners on same thread, use TestMockTimeTaskRunner's "
297 "API instead of RunLoop to drive individual task runners.";
Gabriel Charette2a53350172021-05-06 20:22:55298 DCHECK(run_allowed_);
299 run_allowed_ = false;
gabcf5e4ce2017-05-19 22:56:57300#endif // DCHECK_IS_ON()
jbates@chromium.org8e937c1e2012-06-28 22:57:30301
302 // Allow Quit to be called before Run.
Gabriel Charettefbf3c622020-11-19 14:51:13303 if (quit_called_) {
Bruce Dawson9066bfa2021-10-14 06:17:27304 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop_ExitedEarly",
305 TRACE_ID_LOCAL(this), TRACE_EVENT_FLAG_FLOW_IN);
jbates@chromium.org8e937c1e2012-06-28 22:57:30306 return false;
Gabriel Charettefbf3c622020-11-19 14:51:13307 }
jbates@chromium.org8e937c1e2012-06-28 22:57:30308
Gabriel Charetteb87279d2019-06-27 03:21:04309 auto& active_run_loops = delegate_->active_run_loops_;
310 active_run_loops.push(this);
jbates@chromium.org8e937c1e2012-06-28 22:57:30311
Gabriel Charetteb87279d2019-06-27 03:21:04312 const bool is_nested = active_run_loops.size() > 1;
gab7af9dc02017-05-05 13:38:54313
314 if (is_nested) {
gab273551962017-05-18 06:01:10315 for (auto& observer : delegate_->nesting_observers_)
gab7af9dc02017-05-05 13:38:54316 observer.OnBeginNestedRunLoop();
Gabriel Charette3ff403e2017-08-07 04:22:48317 if (type_ == Type::kNestableTasksAllowed)
318 delegate_->EnsureWorkScheduled();
gab7af9dc02017-05-05 13:38:54319 }
jamescookaacdfd02016-04-28 00:50:03320
jbates@chromium.org8e937c1e2012-06-28 22:57:30321 running_ = true;
322 return true;
323}
324
325void RunLoop::AfterRun() {
gab980a52712017-05-18 16:20:16326 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
gab7af9dc02017-05-05 13:38:54327
jbates@chromium.org8e937c1e2012-06-28 22:57:30328 running_ = false;
329
Bruce Dawson9066bfa2021-10-14 06:17:27330 TRACE_EVENT_WITH_FLOW0("toplevel.flow", "RunLoop_Exited",
331 TRACE_ID_LOCAL(this), TRACE_EVENT_FLAG_FLOW_IN);
Gabriel Charettefbf3c622020-11-19 14:51:13332
Gabriel Charetteb87279d2019-06-27 03:21:04333 auto& active_run_loops = delegate_->active_run_loops_;
334 DCHECK_EQ(active_run_loops.top(), this);
335 active_run_loops.pop();
gab7af9dc02017-05-05 13:38:54336
Gabriel Charetteb87279d2019-06-27 03:21:04337 // Exiting a nested RunLoop?
338 if (!active_run_loops.empty()) {
Francois Doray80bdddf2018-01-04 16:17:32339 for (auto& observer : delegate_->nesting_observers_)
340 observer.OnExitNestedRunLoop();
Francois Doray80bdddf2018-01-04 16:17:32341
Gabriel Charetteb87279d2019-06-27 03:21:04342 // Execute deferred Quit, if any:
343 if (active_run_loops.top()->quit_called_)
344 delegate_->Quit();
345 }
jbates@chromium.org8e937c1e2012-06-28 22:57:30346}
347
348} // namespace base