OLD | NEW |
1 // Copyright 2017 The Chromium Authors. All rights reserved. | 1 // Copyright 2017 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "base/test/scoped_task_environment.h" | 5 #include "base/test/scoped_task_environment.h" |
6 | 6 |
7 #include "base/run_loop.h" | 7 #include "base/run_loop.h" |
8 #include "base/task_scheduler/scheduler_worker_pool_params.h" | 8 #include "base/synchronization/condition_variable.h" |
| 9 #include "base/synchronization/lock.h" |
| 10 #include "base/task_scheduler/post_task.h" |
9 #include "base/task_scheduler/task_scheduler.h" | 11 #include "base/task_scheduler/task_scheduler.h" |
| 12 #include "base/task_scheduler/task_scheduler_impl.h" |
| 13 #include "base/threading/thread_task_runner_handle.h" |
10 #include "base/time/time.h" | 14 #include "base/time/time.h" |
11 | 15 |
12 namespace base { | 16 namespace base { |
13 namespace test { | 17 namespace test { |
14 | 18 |
15 namespace { | 19 namespace { |
16 | 20 |
17 class TaskObserver : public MessageLoop::TaskObserver { | 21 class TaskObserver : public MessageLoop::TaskObserver { |
18 public: | 22 public: |
19 TaskObserver() = default; | 23 TaskObserver() = default; |
20 | 24 |
21 // MessageLoop::TaskObserver: | 25 // MessageLoop::TaskObserver: |
22 void WillProcessTask(const PendingTask& pending_task) override {} | 26 void WillProcessTask(const PendingTask& pending_task) override {} |
23 void DidProcessTask(const PendingTask& pending_task) override { | 27 void DidProcessTask(const PendingTask& pending_task) override { |
24 ran_task_ = true; | 28 ++task_count_; |
25 } | 29 } |
26 | 30 |
27 bool ran_task() const { return ran_task_; } | 31 int task_count() const { return task_count_; } |
28 | 32 |
29 private: | 33 private: |
30 bool ran_task_ = false; | 34 int task_count_ = 0; |
| 35 |
31 DISALLOW_COPY_AND_ASSIGN(TaskObserver); | 36 DISALLOW_COPY_AND_ASSIGN(TaskObserver); |
32 }; | 37 }; |
33 | 38 |
34 } // namespace | 39 } // namespace |
35 | 40 |
36 ScopedTaskEnvironment::ScopedTaskEnvironment(MainThreadType main_thread_type) | 41 class ScopedTaskEnvironment::TestTaskTracker |
37 : message_loop_(main_thread_type == MainThreadType::DEFAULT | 42 : public internal::TaskSchedulerImpl::TaskTrackerType { |
| 43 public: |
| 44 TestTaskTracker(ScopedTaskEnvironment* outer); |
| 45 |
| 46 void SetTaskQueueEmptyClosure(OnceClosure task_queue_empty_closure); |
| 47 |
| 48 // Allow running tasks. |
| 49 void AllowRunRask(); |
| 50 |
| 51 // Disallow running tasks. No-ops and returns false if a task is running. |
| 52 bool DisallowRunTasks(); |
| 53 |
| 54 private: |
| 55 friend class ScopedTaskEnvironment; |
| 56 |
| 57 // internal::TaskSchedulerImpl::TaskTrackerType: |
| 58 void PerformRunTask(std::unique_ptr<internal::Task> task, |
| 59 const SequenceToken& sequence_token) override; |
| 60 |
| 61 ScopedTaskEnvironment* const outer_; |
| 62 |
| 63 // Synchronizes accesses to members below. |
| 64 Lock lock_; |
| 65 |
| 66 // Closure posted to the main thread when the task queue becomes empty. |
| 67 OnceClosure task_queue_empty_closure_; |
| 68 |
| 69 // True if running tasks is allowed. |
| 70 bool can_run_tasks_ = true; |
| 71 |
| 72 // Signaled when |can_run_tasks_| becomes true. |
| 73 ConditionVariable can_run_tasks_cv_; |
| 74 |
| 75 // Number of tasks that are currently running. |
| 76 int num_tasks_running_ = 0; |
| 77 |
| 78 DISALLOW_COPY_AND_ASSIGN(TestTaskTracker); |
| 79 }; |
| 80 |
| 81 ScopedTaskEnvironment::ScopedTaskEnvironment( |
| 82 MainThreadType main_thread_type, |
| 83 ExecutionControlMode execution_control_mode) |
| 84 : execution_control_mode_(execution_control_mode), |
| 85 message_loop_(main_thread_type == MainThreadType::DEFAULT |
38 ? MessageLoop::TYPE_DEFAULT | 86 ? MessageLoop::TYPE_DEFAULT |
39 : (main_thread_type == MainThreadType::UI | 87 : (main_thread_type == MainThreadType::UI |
40 ? MessageLoop::TYPE_UI | 88 ? MessageLoop::TYPE_UI |
41 : MessageLoop::TYPE_IO)) { | 89 : MessageLoop::TYPE_IO)), |
42 DCHECK(!TaskScheduler::GetInstance()); | 90 task_tracker_(new TestTaskTracker(this)) { |
| 91 CHECK(!TaskScheduler::GetInstance()); |
43 | 92 |
44 // Instantiate a TaskScheduler with 1 thread in each of its 4 pools. Threads | 93 // Instantiate a TaskScheduler with 1 thread in each of its 4 pools. Threads |
45 // stay alive even when they don't have work. | 94 // stay alive even when they don't have work. |
46 constexpr int kMaxThreads = 1; | 95 constexpr int kMaxThreads = 1; |
47 const TimeDelta kSuggestedReclaimTime = TimeDelta::Max(); | 96 const TimeDelta kSuggestedReclaimTime = TimeDelta::Max(); |
48 const SchedulerWorkerPoolParams worker_pool_params( | 97 const SchedulerWorkerPoolParams worker_pool_params( |
49 SchedulerWorkerPoolParams::StandbyThreadPolicy::ONE, kMaxThreads, | 98 SchedulerWorkerPoolParams::StandbyThreadPolicy::ONE, kMaxThreads, |
50 kSuggestedReclaimTime); | 99 kSuggestedReclaimTime); |
51 TaskScheduler::Create("ScopedTaskEnvironment"); | 100 TaskScheduler::SetInstance(MakeUnique<internal::TaskSchedulerImpl>( |
| 101 "ScopedTaskEnvironment", WrapUnique(task_tracker_))); |
52 task_scheduler_ = TaskScheduler::GetInstance(); | 102 task_scheduler_ = TaskScheduler::GetInstance(); |
53 TaskScheduler::GetInstance()->Start({worker_pool_params, worker_pool_params, | 103 TaskScheduler::GetInstance()->Start({worker_pool_params, worker_pool_params, |
54 worker_pool_params, worker_pool_params}); | 104 worker_pool_params, worker_pool_params}); |
| 105 |
| 106 if (execution_control_mode_ == ExecutionControlMode::QUEUED) |
| 107 CHECK(task_tracker_->DisallowRunTasks()); |
55 } | 108 } |
56 | 109 |
57 ScopedTaskEnvironment::~ScopedTaskEnvironment() { | 110 ScopedTaskEnvironment::~ScopedTaskEnvironment() { |
58 // Ideally this would RunLoop().RunUntilIdle() here to catch any errors or | 111 // Ideally this would RunLoop().RunUntilIdle() here to catch any errors or |
59 // infinite post loop in the remaining work but this isn't possible right now | 112 // infinite post loop in the remaining work but this isn't possible right now |
60 // because base::~MessageLoop() didn't use to do this and adding it here would | 113 // because base::~MessageLoop() didn't use to do this and adding it here would |
61 // make the migration away from MessageLoop that much harder. | 114 // make the migration away from MessageLoop that much harder. |
62 | 115 CHECK_EQ(TaskScheduler::GetInstance(), task_scheduler_); |
63 DCHECK_EQ(TaskScheduler::GetInstance(), task_scheduler_); | |
64 // Without FlushForTesting(), DeleteSoon() and ReleaseSoon() tasks could be | 116 // Without FlushForTesting(), DeleteSoon() and ReleaseSoon() tasks could be |
65 // skipped, resulting in memory leaks. | 117 // skipped, resulting in memory leaks. |
| 118 task_tracker_->AllowRunRask(); |
66 TaskScheduler::GetInstance()->FlushForTesting(); | 119 TaskScheduler::GetInstance()->FlushForTesting(); |
67 TaskScheduler::GetInstance()->Shutdown(); | 120 TaskScheduler::GetInstance()->Shutdown(); |
68 TaskScheduler::GetInstance()->JoinForTesting(); | 121 TaskScheduler::GetInstance()->JoinForTesting(); |
69 TaskScheduler::SetInstance(nullptr); | 122 TaskScheduler::SetInstance(nullptr); |
70 } | 123 } |
71 | 124 |
72 scoped_refptr<base::SingleThreadTaskRunner> | 125 scoped_refptr<base::SingleThreadTaskRunner> |
73 ScopedTaskEnvironment::GetMainThreadTaskRunner() { | 126 ScopedTaskEnvironment::GetMainThreadTaskRunner() { |
74 return message_loop_.task_runner(); | 127 return message_loop_.task_runner(); |
75 } | 128 } |
76 | 129 |
77 void ScopedTaskEnvironment::RunUntilIdle() { | 130 void ScopedTaskEnvironment::RunUntilIdle() { |
78 for (;;) { | 131 for (;;) { |
79 TaskScheduler::GetInstance()->FlushForTesting(); | 132 RunLoop run_loop; |
80 | 133 |
| 134 // Register a closure to stop running tasks on the main thread when the |
| 135 // TaskScheduler queue becomes empty. |
| 136 task_tracker_->SetTaskQueueEmptyClosure(run_loop.QuitWhenIdleClosure()); |
| 137 |
| 138 // The closure registered above may never run if the TaskScheduler queue |
| 139 // starts empty. Post a TaskScheduler tasks to make sure that the queue |
| 140 // doesn't start empty. |
| 141 PostTask(FROM_HERE, BindOnce(&DoNothing)); |
| 142 |
| 143 // Run main thread and TaskScheduler tasks. |
| 144 task_tracker_->AllowRunRask(); |
81 TaskObserver task_observer; | 145 TaskObserver task_observer; |
82 MessageLoop::current()->AddTaskObserver(&task_observer); | 146 MessageLoop::current()->AddTaskObserver(&task_observer); |
83 RunLoop().RunUntilIdle(); | 147 run_loop.Run(); |
84 MessageLoop::current()->RemoveTaskObserver(&task_observer); | 148 MessageLoop::current()->RemoveTaskObserver(&task_observer); |
85 | 149 |
86 if (!task_observer.ran_task()) | 150 // If the ExecutionControlMode is QUEUED and DisallowRunTasks() fails, |
| 151 // another iteration is required to make sure that RunUntilIdle() doesn't |
| 152 // return while TaskScheduler tasks are still allowed to run. |
| 153 // |
| 154 // If tasks other than the QuitWhenIdle closure ran on the main thread, they |
| 155 // may have posted TaskScheduler tasks that didn't run yet. Another |
| 156 // iteration is required to run them. |
| 157 // |
| 158 // Note: DisallowRunTasks() fails when a TaskScheduler task is running. A |
| 159 // TaskScheduler task may be running after the TaskScheduler queue became |
| 160 // empty even if no tasks ran on the main thread in these cases: |
| 161 // - An undelayed task became ripe for execution. |
| 162 // - A task was posted from an external thread. |
| 163 if ((execution_control_mode_ == ExecutionControlMode::QUEUED && |
| 164 task_tracker_->DisallowRunTasks()) || |
| 165 task_observer.task_count() == 1) { |
87 return; | 166 return; |
| 167 } |
88 } | 168 } |
89 } | 169 } |
90 | 170 |
| 171 ScopedTaskEnvironment::TestTaskTracker::TestTaskTracker( |
| 172 ScopedTaskEnvironment* outer) |
| 173 : outer_(outer), can_run_tasks_cv_(&lock_) {} |
| 174 |
| 175 void ScopedTaskEnvironment::TestTaskTracker::SetTaskQueueEmptyClosure( |
| 176 OnceClosure task_queue_empty_closure) { |
| 177 AutoLock auto_lock(lock_); |
| 178 CHECK(!task_queue_empty_closure_); |
| 179 task_queue_empty_closure_ = std::move(task_queue_empty_closure); |
| 180 } |
| 181 |
| 182 void ScopedTaskEnvironment::TestTaskTracker::AllowRunRask() { |
| 183 AutoLock auto_lock(lock_); |
| 184 can_run_tasks_ = true; |
| 185 can_run_tasks_cv_.Broadcast(); |
| 186 } |
| 187 |
| 188 bool ScopedTaskEnvironment::TestTaskTracker::DisallowRunTasks() { |
| 189 AutoLock auto_lock(lock_); |
| 190 |
| 191 // Can't disallow run task if there are tasks running. |
| 192 if (num_tasks_running_ > 0) |
| 193 return false; |
| 194 |
| 195 can_run_tasks_ = false; |
| 196 return true; |
| 197 } |
| 198 |
| 199 void ScopedTaskEnvironment::TestTaskTracker::PerformRunTask( |
| 200 std::unique_ptr<internal::Task> task, |
| 201 const SequenceToken& sequence_token) { |
| 202 { |
| 203 AutoLock auto_lock(lock_); |
| 204 |
| 205 while (!can_run_tasks_) |
| 206 can_run_tasks_cv_.Wait(); |
| 207 |
| 208 ++num_tasks_running_; |
| 209 } |
| 210 |
| 211 internal::TaskSchedulerImpl::TaskTrackerType::PerformRunTask(std::move(task), |
| 212 sequence_token); |
| 213 |
| 214 { |
| 215 AutoLock auto_lock(lock_); |
| 216 |
| 217 CHECK_GT(num_tasks_running_, 0); |
| 218 CHECK(can_run_tasks_); |
| 219 |
| 220 --num_tasks_running_; |
| 221 |
| 222 // Notify the main thread when no undelayed tasks are queued and no task |
| 223 // other than the current one is running. |
| 224 if (num_tasks_running_ == 0 && |
| 225 GetNumPendingUndelayedTasksForTesting() == 1 && |
| 226 task_queue_empty_closure_) { |
| 227 outer_->GetMainThreadTaskRunner()->PostTask( |
| 228 FROM_HERE, std::move(task_queue_empty_closure_)); |
| 229 } |
| 230 } |
| 231 } |
| 232 |
91 } // namespace test | 233 } // namespace test |
92 } // namespace base | 234 } // namespace base |
OLD | NEW |