| 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/synchronization/condition_variable.h" | 8 #include "base/task_scheduler/scheduler_worker_pool_params.h" |
| 9 #include "base/synchronization/lock.h" | |
| 10 #include "base/task_scheduler/post_task.h" | |
| 11 #include "base/task_scheduler/task_scheduler.h" | 9 #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" | |
| 14 #include "base/time/time.h" | 10 #include "base/time/time.h" |
| 15 | 11 |
| 16 namespace base { | 12 namespace base { |
| 17 namespace test { | 13 namespace test { |
| 18 | 14 |
| 19 namespace { | 15 namespace { |
| 20 | 16 |
| 21 class TaskObserver : public MessageLoop::TaskObserver { | 17 class TaskObserver : public MessageLoop::TaskObserver { |
| 22 public: | 18 public: |
| 23 TaskObserver() = default; | 19 TaskObserver() = default; |
| 24 | 20 |
| 25 // MessageLoop::TaskObserver: | 21 // MessageLoop::TaskObserver: |
| 26 void WillProcessTask(const PendingTask& pending_task) override {} | 22 void WillProcessTask(const PendingTask& pending_task) override {} |
| 27 void DidProcessTask(const PendingTask& pending_task) override { | 23 void DidProcessTask(const PendingTask& pending_task) override { |
| 28 ++task_count_; | 24 ran_task_ = true; |
| 29 } | 25 } |
| 30 | 26 |
| 31 int task_count() const { return task_count_; } | 27 bool ran_task() const { return ran_task_; } |
| 32 | 28 |
| 33 private: | 29 private: |
| 34 int task_count_ = 0; | 30 bool ran_task_ = false; |
| 35 | |
| 36 DISALLOW_COPY_AND_ASSIGN(TaskObserver); | 31 DISALLOW_COPY_AND_ASSIGN(TaskObserver); |
| 37 }; | 32 }; |
| 38 | 33 |
| 39 } // namespace | 34 } // namespace |
| 40 | 35 |
| 41 class ScopedTaskEnvironment::TestTaskTracker | 36 ScopedTaskEnvironment::ScopedTaskEnvironment(MainThreadType main_thread_type) |
| 42 : public internal::TaskSchedulerImpl::TaskTrackerType { | 37 : message_loop_(main_thread_type == MainThreadType::DEFAULT |
| 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 | |
| 86 ? MessageLoop::TYPE_DEFAULT | 38 ? MessageLoop::TYPE_DEFAULT |
| 87 : (main_thread_type == MainThreadType::UI | 39 : (main_thread_type == MainThreadType::UI |
| 88 ? MessageLoop::TYPE_UI | 40 ? MessageLoop::TYPE_UI |
| 89 : MessageLoop::TYPE_IO)), | 41 : MessageLoop::TYPE_IO)) { |
| 90 task_tracker_(new TestTaskTracker(this)) { | 42 DCHECK(!TaskScheduler::GetInstance()); |
| 91 CHECK(!TaskScheduler::GetInstance()); | |
| 92 | 43 |
| 93 // Instantiate a TaskScheduler with 1 thread in each of its 4 pools. Threads | 44 // Instantiate a TaskScheduler with 1 thread in each of its 4 pools. Threads |
| 94 // stay alive even when they don't have work. | 45 // stay alive even when they don't have work. |
| 95 constexpr int kMaxThreads = 1; | 46 constexpr int kMaxThreads = 1; |
| 96 const TimeDelta kSuggestedReclaimTime = TimeDelta::Max(); | 47 const TimeDelta kSuggestedReclaimTime = TimeDelta::Max(); |
| 97 const SchedulerWorkerPoolParams worker_pool_params( | 48 const SchedulerWorkerPoolParams worker_pool_params( |
| 98 SchedulerWorkerPoolParams::StandbyThreadPolicy::ONE, kMaxThreads, | 49 SchedulerWorkerPoolParams::StandbyThreadPolicy::ONE, kMaxThreads, |
| 99 kSuggestedReclaimTime); | 50 kSuggestedReclaimTime); |
| 100 TaskScheduler::SetInstance(MakeUnique<internal::TaskSchedulerImpl>( | 51 TaskScheduler::Create("ScopedTaskEnvironment"); |
| 101 "ScopedTaskEnvironment", WrapUnique(task_tracker_))); | |
| 102 task_scheduler_ = TaskScheduler::GetInstance(); | 52 task_scheduler_ = TaskScheduler::GetInstance(); |
| 103 TaskScheduler::GetInstance()->Start({worker_pool_params, worker_pool_params, | 53 TaskScheduler::GetInstance()->Start({worker_pool_params, worker_pool_params, |
| 104 worker_pool_params, worker_pool_params}); | 54 worker_pool_params, worker_pool_params}); |
| 105 | |
| 106 if (execution_control_mode_ == ExecutionControlMode::QUEUED) | |
| 107 CHECK(task_tracker_->DisallowRunTasks()); | |
| 108 } | 55 } |
| 109 | 56 |
| 110 ScopedTaskEnvironment::~ScopedTaskEnvironment() { | 57 ScopedTaskEnvironment::~ScopedTaskEnvironment() { |
| 111 // Ideally this would RunLoop().RunUntilIdle() here to catch any errors or | 58 // Ideally this would RunLoop().RunUntilIdle() here to catch any errors or |
| 112 // infinite post loop in the remaining work but this isn't possible right now | 59 // infinite post loop in the remaining work but this isn't possible right now |
| 113 // because base::~MessageLoop() didn't use to do this and adding it here would | 60 // because base::~MessageLoop() didn't use to do this and adding it here would |
| 114 // make the migration away from MessageLoop that much harder. | 61 // make the migration away from MessageLoop that much harder. |
| 115 CHECK_EQ(TaskScheduler::GetInstance(), task_scheduler_); | 62 |
| 63 DCHECK_EQ(TaskScheduler::GetInstance(), task_scheduler_); |
| 116 // Without FlushForTesting(), DeleteSoon() and ReleaseSoon() tasks could be | 64 // Without FlushForTesting(), DeleteSoon() and ReleaseSoon() tasks could be |
| 117 // skipped, resulting in memory leaks. | 65 // skipped, resulting in memory leaks. |
| 118 task_tracker_->AllowRunRask(); | |
| 119 TaskScheduler::GetInstance()->FlushForTesting(); | 66 TaskScheduler::GetInstance()->FlushForTesting(); |
| 120 TaskScheduler::GetInstance()->Shutdown(); | 67 TaskScheduler::GetInstance()->Shutdown(); |
| 121 TaskScheduler::GetInstance()->JoinForTesting(); | 68 TaskScheduler::GetInstance()->JoinForTesting(); |
| 122 TaskScheduler::SetInstance(nullptr); | 69 TaskScheduler::SetInstance(nullptr); |
| 123 } | 70 } |
| 124 | 71 |
| 125 scoped_refptr<base::SingleThreadTaskRunner> | 72 scoped_refptr<base::SingleThreadTaskRunner> |
| 126 ScopedTaskEnvironment::GetMainThreadTaskRunner() { | 73 ScopedTaskEnvironment::GetMainThreadTaskRunner() { |
| 127 return message_loop_.task_runner(); | 74 return message_loop_.task_runner(); |
| 128 } | 75 } |
| 129 | 76 |
| 130 void ScopedTaskEnvironment::RunUntilIdle() { | 77 void ScopedTaskEnvironment::RunUntilIdle() { |
| 131 for (;;) { | 78 for (;;) { |
| 132 RunLoop run_loop; | 79 TaskScheduler::GetInstance()->FlushForTesting(); |
| 133 | 80 |
| 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(); | |
| 145 TaskObserver task_observer; | 81 TaskObserver task_observer; |
| 146 MessageLoop::current()->AddTaskObserver(&task_observer); | 82 MessageLoop::current()->AddTaskObserver(&task_observer); |
| 147 run_loop.Run(); | 83 RunLoop().RunUntilIdle(); |
| 148 MessageLoop::current()->RemoveTaskObserver(&task_observer); | 84 MessageLoop::current()->RemoveTaskObserver(&task_observer); |
| 149 | 85 |
| 150 // If the ExecutionControlMode is QUEUED and DisallowRunTasks() fails, | 86 if (!task_observer.ran_task()) |
| 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) { | |
| 166 return; | 87 return; |
| 167 } | |
| 168 } | 88 } |
| 169 } | 89 } |
| 170 | 90 |
| 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 | |
| 233 } // namespace test | 91 } // namespace test |
| 234 } // namespace base | 92 } // namespace base |
| OLD | NEW |