Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(192)

Side by Side Diff: base/task_scheduler/scheduler_thread_pool_impl.cc

Issue 1876363004: TaskScheduler [11] Support ExecutionMode::SINGLE_THREADED. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@8_delayed
Patch Set: self review Created 4 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 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/task_scheduler/scheduler_thread_pool_impl.h" 5 #include "base/task_scheduler/scheduler_thread_pool_impl.h"
6 6
7 #include <utility> 7 #include <utility>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/bind_helpers.h" 10 #include "base/bind_helpers.h"
11 #include "base/lazy_instance.h" 11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/memory/ptr_util.h" 12 #include "base/memory/ptr_util.h"
14 #include "base/sequenced_task_runner.h" 13 #include "base/sequenced_task_runner.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/task_scheduler/delayed_task_manager.h" 15 #include "base/task_scheduler/delayed_task_manager.h"
16 #include "base/task_scheduler/task_tracker.h" 16 #include "base/task_scheduler/task_tracker.h"
17 #include "base/threading/thread_local.h" 17 #include "base/threading/thread_local.h"
18 18
19 namespace base { 19 namespace base {
20 namespace internal { 20 namespace internal {
21 21
22 namespace { 22 namespace {
23 23
24 // SchedulerThreadPool that owns the current thread, if any. 24 // SchedulerThreadPool that owns the current thread, if any.
25 LazyInstance<ThreadLocalPointer<const SchedulerThreadPool>>::Leaky 25 LazyInstance<ThreadLocalPointer<const SchedulerThreadPool>>::Leaky
26 tls_current_thread_pool = LAZY_INSTANCE_INITIALIZER; 26 tls_current_thread_pool = LAZY_INSTANCE_INITIALIZER;
27 27
28 // SchedulerWorkerThread that owns the current thread, if any.
29 LazyInstance<ThreadLocalPointer<const SchedulerWorkerThread>>::Leaky
30 tls_current_worker_thread = LAZY_INSTANCE_INITIALIZER;
31
28 // A task runner that runs tasks with the PARALLEL ExecutionMode. 32 // A task runner that runs tasks with the PARALLEL ExecutionMode.
29 class SchedulerParallelTaskRunner : public TaskRunner { 33 class SchedulerParallelTaskRunner : public TaskRunner {
30 public: 34 public:
31 // Constructs a SchedulerParallelTaskRunner which can be used to post tasks so 35 // Constructs a SchedulerParallelTaskRunner which can be used to post tasks so
32 // long as |thread_pool| is alive. 36 // long as |thread_pool| is alive.
33 // TODO(robliao): Find a concrete way to manage |thread_pool|'s memory. 37 // TODO(robliao): Find a concrete way to manage |thread_pool|'s memory.
34 SchedulerParallelTaskRunner(const TaskTraits& traits, 38 SchedulerParallelTaskRunner(const TaskTraits& traits,
35 SchedulerThreadPool* thread_pool) 39 SchedulerThreadPool* thread_pool)
36 : traits_(traits), thread_pool_(thread_pool) {} 40 : traits_(traits), thread_pool_(thread_pool) {}
37 41
38 // TaskRunner: 42 // TaskRunner:
39 bool PostDelayedTask(const tracked_objects::Location& from_here, 43 bool PostDelayedTask(const tracked_objects::Location& from_here,
40 const Closure& closure, 44 const Closure& closure,
41 TimeDelta delay) override { 45 TimeDelta delay) override {
42 // Post the task as part of a one-off single-task Sequence. 46 // Post the task as part of a one-off single-task Sequence.
43 return thread_pool_->PostTaskWithSequence( 47 return thread_pool_->PostTaskWithSequence(
44 WrapUnique(new Task(from_here, closure, traits_, delay)), 48 WrapUnique(new Task(from_here, closure, traits_, delay)),
45 make_scoped_refptr(new Sequence)); 49 make_scoped_refptr(new Sequence), nullptr);
46 } 50 }
47 51
48 bool RunsTasksOnCurrentThread() const override { 52 bool RunsTasksOnCurrentThread() const override {
49 return tls_current_thread_pool.Get().Get() == thread_pool_; 53 return tls_current_thread_pool.Get().Get() == thread_pool_;
50 } 54 }
51 55
52 private: 56 private:
53 ~SchedulerParallelTaskRunner() override = default; 57 ~SchedulerParallelTaskRunner() override = default;
54 58
55 const TaskTraits traits_; 59 const TaskTraits traits_;
56 SchedulerThreadPool* const thread_pool_; 60 SchedulerThreadPool* const thread_pool_;
57 61
58 DISALLOW_COPY_AND_ASSIGN(SchedulerParallelTaskRunner); 62 DISALLOW_COPY_AND_ASSIGN(SchedulerParallelTaskRunner);
59 }; 63 };
60 64
61 // A task runner that runs tasks with the SEQUENCED ExecutionMode. 65 // A task runner that runs tasks with the SEQUENCED ExecutionMode.
62 class SchedulerSequencedTaskRunner : public SequencedTaskRunner { 66 class SchedulerSequencedTaskRunner : public SequencedTaskRunner {
63 public: 67 public:
64 // Constructs a SchedulerSequencedTaskRunner which can be used to post tasks 68 // Constructs a SchedulerSequencedTaskRunner which can be used to post tasks
65 // so long as |thread_pool| is alive. 69 // so long as |thread_pool| is alive.
66 // TODO(robliao): Find a concrete way to manage |thread_pool|'s memory. 70 // TODO(robliao): Find a concrete way to manage |thread_pool|'s memory.
67 SchedulerSequencedTaskRunner(const TaskTraits& traits, 71 SchedulerSequencedTaskRunner(const TaskTraits& traits,
68 SchedulerThreadPool* thread_pool) 72 SchedulerThreadPool* thread_pool)
69 : traits_(traits), thread_pool_(thread_pool) {} 73 : traits_(traits), thread_pool_(thread_pool) {}
70 74
71 // SequencedTaskRunner: 75 // SequencedTaskRunner:
72 bool PostDelayedTask(const tracked_objects::Location& from_here, 76 bool PostDelayedTask(const tracked_objects::Location& from_here,
73 const Closure& closure, 77 const Closure& closure,
74 TimeDelta delay) override { 78 TimeDelta delay) override {
75 // Post the task as part of |sequence|. 79 // Post the task as part of |sequence_|.
76 return thread_pool_->PostTaskWithSequence( 80 return thread_pool_->PostTaskWithSequence(
77 WrapUnique(new Task(from_here, closure, traits_, delay)), sequence_); 81 WrapUnique(new Task(from_here, closure, traits_, delay)), sequence_,
82 nullptr);
78 } 83 }
79 84
80 bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here, 85 bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
81 const Closure& closure, 86 const Closure& closure,
82 base::TimeDelta delay) override { 87 base::TimeDelta delay) override {
83 // Tasks are never nested within the task scheduler. 88 // Tasks are never nested within the task scheduler.
84 return PostDelayedTask(from_here, closure, delay); 89 return PostDelayedTask(from_here, closure, delay);
85 } 90 }
86 91
87 bool RunsTasksOnCurrentThread() const override { 92 bool RunsTasksOnCurrentThread() const override {
88 return tls_current_thread_pool.Get().Get() == thread_pool_; 93 return tls_current_thread_pool.Get().Get() == thread_pool_;
89 } 94 }
90 95
91 private: 96 private:
92 ~SchedulerSequencedTaskRunner() override = default; 97 ~SchedulerSequencedTaskRunner() override = default;
93 98
94 // Sequence for all Tasks posted through this TaskRunner. 99 // Sequence for all Tasks posted through this TaskRunner.
95 const scoped_refptr<Sequence> sequence_ = new Sequence; 100 const scoped_refptr<Sequence> sequence_ = new Sequence;
96 101
97 const TaskTraits traits_; 102 const TaskTraits traits_;
98 SchedulerThreadPool* const thread_pool_; 103 SchedulerThreadPool* const thread_pool_;
99 104
100 DISALLOW_COPY_AND_ASSIGN(SchedulerSequencedTaskRunner); 105 DISALLOW_COPY_AND_ASSIGN(SchedulerSequencedTaskRunner);
101 }; 106 };
102 107
108 // A task runner that runs tasks with the SINGLE_THREADED ExecutionMode.
109 class SchedulerSingleThreadTaskRunner : public SingleThreadTaskRunner {
110 public:
111 // Constructs a SchedulerSingleThreadTaskRunner which can be used to post
112 // tasks so long as |thread_pool| and |worker_thread| are alive.
113 // TODO(robliao): Find a concrete way to manage the memory of |thread_pool|
114 // and |worker_thread|.
115 SchedulerSingleThreadTaskRunner(const TaskTraits& traits,
116 SchedulerThreadPool* thread_pool,
117 SchedulerWorkerThread* worker_thread)
118 : traits_(traits),
119 thread_pool_(thread_pool),
120 worker_thread_(worker_thread) {}
121
122 // SingleThreadTaskRunner:
123 bool PostDelayedTask(const tracked_objects::Location& from_here,
124 const Closure& closure,
125 TimeDelta delay) override {
126 // Post the task to be executed by |worker_thread_| as part of |sequence_|.
127 return thread_pool_->PostTaskWithSequence(
128 WrapUnique(new Task(from_here, closure, traits_, delay)), sequence_,
129 worker_thread_);
130 }
131
132 bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
133 const Closure& closure,
134 base::TimeDelta delay) override {
135 // Tasks are never nested within the task scheduler.
136 return PostDelayedTask(from_here, closure, delay);
137 }
138
139 bool RunsTasksOnCurrentThread() const override {
140 return tls_current_worker_thread.Get().Get() == worker_thread_;
141 }
142
143 private:
144 ~SchedulerSingleThreadTaskRunner() override = default;
145
146 // Sequence for all Tasks posted through this TaskRunner.
147 const scoped_refptr<Sequence> sequence_ = new Sequence;
148
149 const TaskTraits traits_;
150 SchedulerThreadPool* const thread_pool_;
151 SchedulerWorkerThread* const worker_thread_;
152
153 DISALLOW_COPY_AND_ASSIGN(SchedulerSingleThreadTaskRunner);
154 };
155
156 // Only used in DCHECKs.
157 bool ContainsWorkerThread(
158 const std::vector<std::unique_ptr<SchedulerWorkerThread>>& worker_threads,
159 const SchedulerWorkerThread* worker_thread) {
160 auto it = std::find_if(
gab 2016/04/28 13:40:03 #include <algorithm> (I think that's the bot erro
fdoray 2016/04/28 13:54:21 Done.
161 worker_threads.begin(), worker_threads.end(),
162 [worker_thread](const std::unique_ptr<SchedulerWorkerThread>& i) {
163 return i.get() == worker_thread;
164 });
165 return it != worker_threads.end();
166 }
167
103 } // namespace 168 } // namespace
104 169
105 class SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl 170 class SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl
106 : public SchedulerWorkerThread::Delegate { 171 : public SchedulerWorkerThread::Delegate {
107 public: 172 public:
173 // |outer| owns the worker thread for which this delegate is constructed.
174 // |re_enqueue_sequence_callback| is invoked when ReEnqueueSequence() is
175 // called with a non-single-threaded Sequence. |shared_priority_queue| is a
176 // PriorityQueue whose transactions may overlap with the worker thread's
177 // single-threaded PriorityQueue's transactions.
108 SchedulerWorkerThreadDelegateImpl( 178 SchedulerWorkerThreadDelegateImpl(
109 SchedulerThreadPoolImpl* outer, 179 SchedulerThreadPoolImpl* outer,
110 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback); 180 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback,
181 const PriorityQueue* shared_priority_queue);
111 ~SchedulerWorkerThreadDelegateImpl() override; 182 ~SchedulerWorkerThreadDelegateImpl() override;
112 183
184 PriorityQueue* single_threaded_priority_queue() {
185 return &single_threaded_priority_queue_;
186 }
187
113 // SchedulerWorkerThread::Delegate: 188 // SchedulerWorkerThread::Delegate:
114 void OnMainEntry() override; 189 void OnMainEntry(SchedulerWorkerThread* worker_thread) override;
115 scoped_refptr<Sequence> GetWork( 190 scoped_refptr<Sequence> GetWork(
116 SchedulerWorkerThread* worker_thread) override; 191 SchedulerWorkerThread* worker_thread) override;
117 void ReEnqueueSequence(scoped_refptr<Sequence> sequence) override; 192 void ReEnqueueSequence(scoped_refptr<Sequence> sequence) override;
118 193
119 private: 194 private:
120 SchedulerThreadPoolImpl* outer_; 195 SchedulerThreadPoolImpl* outer_;
121 const ReEnqueueSequenceCallback re_enqueue_sequence_callback_; 196 const ReEnqueueSequenceCallback re_enqueue_sequence_callback_;
122 197
198 // Single-threaded PriorityQueue for the worker thread.
199 PriorityQueue single_threaded_priority_queue_;
200
201 // True if the last Sequence returned by GetWork() was extracted from
202 // |single_threaded_priority_queue_|.
203 bool last_sequence_is_single_threaded_ = false;
204
123 DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerThreadDelegateImpl); 205 DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerThreadDelegateImpl);
124 }; 206 };
125 207
126 SchedulerThreadPoolImpl::~SchedulerThreadPoolImpl() { 208 SchedulerThreadPoolImpl::~SchedulerThreadPoolImpl() {
127 // SchedulerThreadPool should never be deleted in production unless its 209 // SchedulerThreadPool should never be deleted in production unless its
128 // initialization failed. 210 // initialization failed.
129 DCHECK(join_for_testing_returned_.IsSignaled() || worker_threads_.empty()); 211 DCHECK(join_for_testing_returned_.IsSignaled() || worker_threads_.empty());
130 } 212 }
131 213
214 // static
132 std::unique_ptr<SchedulerThreadPoolImpl> SchedulerThreadPoolImpl::Create( 215 std::unique_ptr<SchedulerThreadPoolImpl> SchedulerThreadPoolImpl::Create(
133 ThreadPriority thread_priority, 216 ThreadPriority thread_priority,
134 size_t max_threads, 217 size_t max_threads,
135 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback, 218 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback,
136 TaskTracker* task_tracker, 219 TaskTracker* task_tracker,
137 DelayedTaskManager* delayed_task_manager) { 220 DelayedTaskManager* delayed_task_manager) {
138 std::unique_ptr<SchedulerThreadPoolImpl> thread_pool( 221 std::unique_ptr<SchedulerThreadPoolImpl> thread_pool(
139 new SchedulerThreadPoolImpl(task_tracker, delayed_task_manager)); 222 new SchedulerThreadPoolImpl(task_tracker, delayed_task_manager));
140 if (thread_pool->Initialize(thread_priority, max_threads, 223 if (thread_pool->Initialize(thread_priority, max_threads,
141 re_enqueue_sequence_callback)) { 224 re_enqueue_sequence_callback)) {
(...skipping 19 matching lines...) Expand all
161 scoped_refptr<TaskRunner> SchedulerThreadPoolImpl::CreateTaskRunnerWithTraits( 244 scoped_refptr<TaskRunner> SchedulerThreadPoolImpl::CreateTaskRunnerWithTraits(
162 const TaskTraits& traits, 245 const TaskTraits& traits,
163 ExecutionMode execution_mode) { 246 ExecutionMode execution_mode) {
164 switch (execution_mode) { 247 switch (execution_mode) {
165 case ExecutionMode::PARALLEL: 248 case ExecutionMode::PARALLEL:
166 return make_scoped_refptr(new SchedulerParallelTaskRunner(traits, this)); 249 return make_scoped_refptr(new SchedulerParallelTaskRunner(traits, this));
167 250
168 case ExecutionMode::SEQUENCED: 251 case ExecutionMode::SEQUENCED:
169 return make_scoped_refptr(new SchedulerSequencedTaskRunner(traits, this)); 252 return make_scoped_refptr(new SchedulerSequencedTaskRunner(traits, this));
170 253
171 case ExecutionMode::SINGLE_THREADED: 254 case ExecutionMode::SINGLE_THREADED: {
172 // TODO(fdoray): Support SINGLE_THREADED TaskRunners. 255 // TODO(fdoray): Find a way to take load into account when assigning a
173 NOTREACHED(); 256 // SchedulerWorkerThread to a SingleThreadTaskRunner. Also, this code
174 return nullptr; 257 // assumes that all SchedulerWorkerThreads are alive. Eventually, we might
258 // decide to tear down threads that haven't run tasks for a long time.
259 size_t worker_thread_index;
260 {
261 AutoSchedulerLock auto_lock(next_worker_thread_index_lock_);
262 worker_thread_index = next_worker_thread_index_;
263 next_worker_thread_index_ =
264 (next_worker_thread_index_ + 1) % worker_threads_.size();
265 }
266 return make_scoped_refptr(new SchedulerSingleThreadTaskRunner(
267 traits, this, worker_threads_[worker_thread_index].get()));
268 }
175 } 269 }
176 270
177 NOTREACHED(); 271 NOTREACHED();
178 return nullptr; 272 return nullptr;
179 } 273 }
180 274
181 void SchedulerThreadPoolImpl::ReEnqueueSequence( 275 void SchedulerThreadPoolImpl::ReEnqueueSequence(
182 scoped_refptr<Sequence> sequence, 276 scoped_refptr<Sequence> sequence,
183 const SequenceSortKey& sequence_sort_key) { 277 const SequenceSortKey& sequence_sort_key) {
184 shared_priority_queue_.BeginTransaction()->Push( 278 shared_priority_queue_.BeginTransaction()->Push(
185 WrapUnique(new PriorityQueue::SequenceAndSortKey(std::move(sequence), 279 WrapUnique(new PriorityQueue::SequenceAndSortKey(std::move(sequence),
186 sequence_sort_key))); 280 sequence_sort_key)));
187 281
188 // The thread calling this method just ran a Task from |sequence| and will 282 // The thread calling this method just ran a Task from |sequence| and will
189 // soon try to get another Sequence from which to run a Task. If the thread 283 // soon try to get another Sequence from which to run a Task. If the thread
190 // belongs to this pool, it will get that Sequence from 284 // belongs to this pool, it will get that Sequence from
191 // |shared_priority_queue_|. When that's the case, there is no need to wake up 285 // |shared_priority_queue_|. When that's the case, there is no need to wake up
192 // another thread after |sequence| is inserted in |shared_priority_queue_|. If 286 // another thread after |sequence| is inserted in |shared_priority_queue_|. If
193 // we did wake up another thread, we would waste resources by having more 287 // we did wake up another thread, we would waste resources by having more
194 // threads trying to get a Sequence from |shared_priority_queue_| than the 288 // threads trying to get a Sequence from |shared_priority_queue_| than the
195 // number of Sequences in it. 289 // number of Sequences in it.
196 if (tls_current_thread_pool.Get().Get() != this) 290 if (tls_current_thread_pool.Get().Get() != this)
197 WakeUpOneThread(); 291 WakeUpOneThread();
198 } 292 }
199 293
200 bool SchedulerThreadPoolImpl::PostTaskWithSequence( 294 bool SchedulerThreadPoolImpl::PostTaskWithSequence(
201 std::unique_ptr<Task> task, 295 std::unique_ptr<Task> task,
202 scoped_refptr<Sequence> sequence) { 296 scoped_refptr<Sequence> sequence,
297 SchedulerWorkerThread* worker_thread) {
203 DCHECK(task); 298 DCHECK(task);
204 DCHECK(sequence); 299 DCHECK(sequence);
300 DCHECK(!worker_thread ||
301 ContainsWorkerThread(worker_threads_, worker_thread));
205 302
206 if (!task_tracker_->WillPostTask(task.get())) 303 if (!task_tracker_->WillPostTask(task.get()))
207 return false; 304 return false;
208 305
209 if (task->delayed_run_time.is_null()) { 306 if (task->delayed_run_time.is_null()) {
210 PostTaskWithSequenceNow(std::move(task), std::move(sequence)); 307 PostTaskWithSequenceNow(std::move(task), std::move(sequence),
308 worker_thread);
211 } else { 309 } else {
212 delayed_task_manager_->AddDelayedTask(std::move(task), std::move(sequence), 310 delayed_task_manager_->AddDelayedTask(std::move(task), std::move(sequence),
213 this); 311 worker_thread, this);
214 } 312 }
215 313
216 return true; 314 return true;
217 } 315 }
218 316
219 void SchedulerThreadPoolImpl::PostTaskWithSequenceNow( 317 void SchedulerThreadPoolImpl::PostTaskWithSequenceNow(
220 std::unique_ptr<Task> task, 318 std::unique_ptr<Task> task,
221 scoped_refptr<Sequence> sequence) { 319 scoped_refptr<Sequence> sequence,
320 SchedulerWorkerThread* worker_thread) {
222 DCHECK(task); 321 DCHECK(task);
223 DCHECK(sequence); 322 DCHECK(sequence);
323 DCHECK(!worker_thread ||
324 ContainsWorkerThread(worker_threads_, worker_thread));
224 325
225 // Confirm that |task| is ready to run (its delayed run time is either null or 326 // Confirm that |task| is ready to run (its delayed run time is either null or
226 // in the past). 327 // in the past).
227 DCHECK_LE(task->delayed_run_time, delayed_task_manager_->Now()); 328 DCHECK_LE(task->delayed_run_time, delayed_task_manager_->Now());
228 329
330 // Because |worker_thread| belongs to this thread pool, we know that the type
331 // of its delegate is SchedulerWorkerThreadDelegateImpl.
332 PriorityQueue* const priority_queue =
333 worker_thread
334 ? static_cast<SchedulerWorkerThreadDelegateImpl*>(
335 worker_thread->delegate())
336 ->single_threaded_priority_queue()
337 : &shared_priority_queue_;
338 DCHECK(priority_queue);
339
229 const bool sequence_was_empty = sequence->PushTask(std::move(task)); 340 const bool sequence_was_empty = sequence->PushTask(std::move(task));
230 if (sequence_was_empty) { 341 if (sequence_was_empty) {
231 // Insert |sequence| in |shared_priority_queue_| if it was empty before 342 // Insert |sequence| in |priority_queue| if it was empty before |task| was
232 // |task| was inserted into it. Otherwise, one of these must be true: 343 // inserted into it. Otherwise, one of these must be true:
233 // - |sequence| is already in a PriorityQueue (not necessarily 344 // - |sequence| is already in a PriorityQueue (not necessarily
234 // |shared_priority_queue_|), or, 345 // |shared_priority_queue_|), or,
235 // - A worker thread is running a Task from |sequence|. It will insert 346 // - A worker thread is running a Task from |sequence|. It will insert
236 // |sequence| in a PriorityQueue once it's done running the Task. 347 // |sequence| in a PriorityQueue once it's done running the Task.
237 const auto sequence_sort_key = sequence->GetSortKey(); 348 const auto sequence_sort_key = sequence->GetSortKey();
238 shared_priority_queue_.BeginTransaction()->Push( 349 priority_queue->BeginTransaction()->Push(
239 WrapUnique(new PriorityQueue::SequenceAndSortKey(std::move(sequence), 350 WrapUnique(new PriorityQueue::SequenceAndSortKey(std::move(sequence),
240 sequence_sort_key))); 351 sequence_sort_key)));
241 352
242 // Wake up a worker thread to process |sequence|. 353 // Wake up a worker thread to process |sequence|.
243 WakeUpOneThread(); 354 if (worker_thread)
355 worker_thread->WakeUp();
356 else
357 WakeUpOneThread();
244 } 358 }
245 } 359 }
246 360
247 SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl:: 361 SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::
248 SchedulerWorkerThreadDelegateImpl( 362 SchedulerWorkerThreadDelegateImpl(
249 SchedulerThreadPoolImpl* outer, 363 SchedulerThreadPoolImpl* outer,
250 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback) 364 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback,
365 const PriorityQueue* shared_priority_queue)
251 : outer_(outer), 366 : outer_(outer),
252 re_enqueue_sequence_callback_(re_enqueue_sequence_callback) {} 367 re_enqueue_sequence_callback_(re_enqueue_sequence_callback),
368 single_threaded_priority_queue_(shared_priority_queue) {}
253 369
254 SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl:: 370 SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::
255 ~SchedulerWorkerThreadDelegateImpl() = default; 371 ~SchedulerWorkerThreadDelegateImpl() = default;
256 372
257 void SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::OnMainEntry() { 373 void SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::OnMainEntry(
374 SchedulerWorkerThread* worker_thread) {
375 #if DCHECK_IS_ON()
376 // Wait for |outer_->threads_created_| to avoid traversing
377 // |outer_->worker_threads_| while it is being filled by Initialize().
378 outer_->threads_created_.Wait();
379 DCHECK(ContainsWorkerThread(outer_->worker_threads_, worker_thread));
380 #endif
381
382 DCHECK(!tls_current_worker_thread.Get().Get());
258 DCHECK(!tls_current_thread_pool.Get().Get()); 383 DCHECK(!tls_current_thread_pool.Get().Get());
384 tls_current_worker_thread.Get().Set(worker_thread);
259 tls_current_thread_pool.Get().Set(outer_); 385 tls_current_thread_pool.Get().Set(outer_);
260 } 386 }
261 387
262 scoped_refptr<Sequence> 388 scoped_refptr<Sequence>
263 SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::GetWork( 389 SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::GetWork(
264 SchedulerWorkerThread* worker_thread) { 390 SchedulerWorkerThread* worker_thread) {
265 std::unique_ptr<PriorityQueue::Transaction> transaction( 391 DCHECK(ContainsWorkerThread(outer_->worker_threads_, worker_thread));
266 outer_->shared_priority_queue_.BeginTransaction());
267 const auto& sequence_and_sort_key = transaction->Peek();
268 392
269 if (sequence_and_sort_key.is_null()) { 393 scoped_refptr<Sequence> sequence;
270 // |transaction| is kept alive while |worker_thread| is added to 394 {
271 // |idle_worker_threads_stack_| to avoid this race: 395 std::unique_ptr<PriorityQueue::Transaction> shared_transaction(
272 // 1. This thread creates a Transaction, finds |shared_priority_queue_| 396 outer_->shared_priority_queue_.BeginTransaction());
273 // empty and ends the Transaction. 397 const auto& shared_sequence_and_sort_key = shared_transaction->Peek();
274 // 2. Other thread creates a Transaction, inserts a Sequence into 398
275 // |shared_priority_queue_| and ends the Transaction. This can't happen 399 std::unique_ptr<PriorityQueue::Transaction> single_threaded_transaction(
276 // if the Transaction of step 1 is still active because because there can 400 single_threaded_priority_queue_.BeginTransaction());
277 // only be one active Transaction per PriorityQueue at a time. 401 const auto& single_threaded_sequence_and_sort_key =
278 // 3. Other thread calls WakeUpOneThread(). No thread is woken up because 402 single_threaded_transaction->Peek();
279 // |idle_worker_threads_stack_| is empty. 403
280 // 4. This thread adds itself to |idle_worker_threads_stack_| and goes to 404 if (shared_sequence_and_sort_key.is_null() &&
281 // sleep. No thread runs the Sequence inserted in step 2. 405 single_threaded_sequence_and_sort_key.is_null()) {
282 outer_->AddToIdleWorkerThreadsStack(worker_thread); 406 single_threaded_transaction.reset();
283 return nullptr; 407
408 // |shared_transaction| is kept alive while |worker_thread| is added to
409 // |idle_worker_threads_stack_| to avoid this race:
410 // 1. This thread creates a Transaction, finds |shared_priority_queue_|
411 // empty and ends the Transaction.
412 // 2. Other thread creates a Transaction, inserts a Sequence into
413 // |shared_priority_queue_| and ends the Transaction. This can't happen
414 // if the Transaction of step 1 is still active because because there
415 // can only be one active Transaction per PriorityQueue at a time.
416 // 3. Other thread calls WakeUpOneThread(). No thread is woken up because
417 // |idle_worker_threads_stack_| is empty.
418 // 4. This thread adds itself to |idle_worker_threads_stack_| and goes to
419 // sleep. No thread runs the Sequence inserted in step 2.
420 outer_->AddToIdleWorkerThreadsStack(worker_thread);
421 return nullptr;
422 }
423
424 // True if both PriorityQueues have Sequences and the Sequence at the top of
425 // the shared PriorityQueue is more important.
426 const bool shared_sequence_is_more_important =
427 !shared_sequence_and_sort_key.is_null() &&
428 !single_threaded_sequence_and_sort_key.is_null() &&
429 shared_sequence_and_sort_key.sort_key >
430 single_threaded_sequence_and_sort_key.sort_key;
431
432 if (single_threaded_sequence_and_sort_key.is_null() ||
433 shared_sequence_is_more_important) {
434 sequence = shared_sequence_and_sort_key.sequence;
435 shared_transaction->Pop();
436 last_sequence_is_single_threaded_ = false;
437 } else {
438 DCHECK(!single_threaded_sequence_and_sort_key.is_null());
439 sequence = single_threaded_sequence_and_sort_key.sequence;
440 single_threaded_transaction->Pop();
441 last_sequence_is_single_threaded_ = true;
442 }
284 } 443 }
444 DCHECK(sequence);
285 445
286 scoped_refptr<Sequence> sequence = sequence_and_sort_key.sequence; 446 outer_->RemoveFromIdleWorkerThreadsStack(worker_thread);
287 transaction->Pop();
288 return sequence; 447 return sequence;
289 } 448 }
290 449
291 void SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl:: 450 void SchedulerThreadPoolImpl::SchedulerWorkerThreadDelegateImpl::
292 ReEnqueueSequence(scoped_refptr<Sequence> sequence) { 451 ReEnqueueSequence(scoped_refptr<Sequence> sequence) {
293 re_enqueue_sequence_callback_.Run(std::move(sequence)); 452 if (last_sequence_is_single_threaded_) {
453 // A single-threaded Sequence is always re-enqueued in the single-threaded
454 // PriorityQueue from which it was extracted.
455 const SequenceSortKey sequence_sort_key = sequence->GetSortKey();
456 single_threaded_priority_queue_.BeginTransaction()->Push(
457 WrapUnique(new PriorityQueue::SequenceAndSortKey(std::move(sequence),
458 sequence_sort_key)));
459 } else {
460 // |re_enqueue_sequence_callback_| will determine in which PriorityQueue
461 // |sequence| must be enqueued.
462 re_enqueue_sequence_callback_.Run(std::move(sequence));
463 }
294 } 464 }
295 465
296 SchedulerThreadPoolImpl::SchedulerThreadPoolImpl( 466 SchedulerThreadPoolImpl::SchedulerThreadPoolImpl(
297 TaskTracker* task_tracker, 467 TaskTracker* task_tracker,
298 DelayedTaskManager* delayed_task_manager) 468 DelayedTaskManager* delayed_task_manager)
299 : idle_worker_threads_stack_lock_(shared_priority_queue_.container_lock()), 469 : idle_worker_threads_stack_lock_(shared_priority_queue_.container_lock()),
300 idle_worker_threads_stack_cv_for_testing_( 470 idle_worker_threads_stack_cv_for_testing_(
301 idle_worker_threads_stack_lock_.CreateConditionVariable()), 471 idle_worker_threads_stack_lock_.CreateConditionVariable()),
302 join_for_testing_returned_(true, false), 472 join_for_testing_returned_(true, false),
473 #if DCHECK_IS_ON()
474 threads_created_(true, false),
475 #endif
303 task_tracker_(task_tracker), 476 task_tracker_(task_tracker),
304 delayed_task_manager_(delayed_task_manager) { 477 delayed_task_manager_(delayed_task_manager) {
305 DCHECK(task_tracker_); 478 DCHECK(task_tracker_);
306 DCHECK(delayed_task_manager_); 479 DCHECK(delayed_task_manager_);
307 } 480 }
308 481
309 bool SchedulerThreadPoolImpl::Initialize( 482 bool SchedulerThreadPoolImpl::Initialize(
310 ThreadPriority thread_priority, 483 ThreadPriority thread_priority,
311 size_t max_threads, 484 size_t max_threads,
312 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback) { 485 const ReEnqueueSequenceCallback& re_enqueue_sequence_callback) {
313 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_); 486 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_);
314 487
315 DCHECK(worker_threads_.empty()); 488 DCHECK(worker_threads_.empty());
316 489
317 for (size_t i = 0; i < max_threads; ++i) { 490 for (size_t i = 0; i < max_threads; ++i) {
318 std::unique_ptr<SchedulerWorkerThread> worker_thread = 491 std::unique_ptr<SchedulerWorkerThread> worker_thread =
319 SchedulerWorkerThread::Create( 492 SchedulerWorkerThread::Create(
320 thread_priority, WrapUnique(new SchedulerWorkerThreadDelegateImpl( 493 thread_priority,
321 this, re_enqueue_sequence_callback)), 494 WrapUnique(new SchedulerWorkerThreadDelegateImpl(
495 this, re_enqueue_sequence_callback, &shared_priority_queue_)),
322 task_tracker_); 496 task_tracker_);
323 if (!worker_thread) 497 if (!worker_thread)
324 break; 498 break;
325 idle_worker_threads_stack_.Push(worker_thread.get()); 499 idle_worker_threads_stack_.Push(worker_thread.get());
326 worker_threads_.push_back(std::move(worker_thread)); 500 worker_threads_.push_back(std::move(worker_thread));
327 } 501 }
328 502
503 #if DCHECK_IS_ON()
504 threads_created_.Signal();
505 #endif
506
329 return !worker_threads_.empty(); 507 return !worker_threads_.empty();
330 } 508 }
331 509
332 void SchedulerThreadPoolImpl::WakeUpOneThread() { 510 void SchedulerThreadPoolImpl::WakeUpOneThread() {
333 SchedulerWorkerThread* worker_thread; 511 SchedulerWorkerThread* worker_thread;
334 { 512 {
335 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_); 513 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_);
336 worker_thread = idle_worker_threads_stack_.Pop(); 514 worker_thread = idle_worker_threads_stack_.Pop();
337 } 515 }
338 if (worker_thread) 516 if (worker_thread)
339 worker_thread->WakeUp(); 517 worker_thread->WakeUp();
340 } 518 }
341 519
342 void SchedulerThreadPoolImpl::AddToIdleWorkerThreadsStack( 520 void SchedulerThreadPoolImpl::AddToIdleWorkerThreadsStack(
343 SchedulerWorkerThread* worker_thread) { 521 SchedulerWorkerThread* worker_thread) {
344 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_); 522 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_);
345 idle_worker_threads_stack_.Push(worker_thread); 523 idle_worker_threads_stack_.Push(worker_thread);
346 DCHECK_LE(idle_worker_threads_stack_.Size(), worker_threads_.size()); 524 DCHECK_LE(idle_worker_threads_stack_.Size(), worker_threads_.size());
347 525
348 if (idle_worker_threads_stack_.Size() == worker_threads_.size()) 526 if (idle_worker_threads_stack_.Size() == worker_threads_.size())
349 idle_worker_threads_stack_cv_for_testing_->Broadcast(); 527 idle_worker_threads_stack_cv_for_testing_->Broadcast();
350 } 528 }
351 529
530 void SchedulerThreadPoolImpl::RemoveFromIdleWorkerThreadsStack(
531 SchedulerWorkerThread* worker_thread) {
532 AutoSchedulerLock auto_lock(idle_worker_threads_stack_lock_);
533 idle_worker_threads_stack_.Remove(worker_thread);
534 }
535
352 } // namespace internal 536 } // namespace internal
353 } // namespace base 537 } // namespace base
OLDNEW
« no previous file with comments | « base/task_scheduler/scheduler_thread_pool_impl.h ('k') | base/task_scheduler/scheduler_thread_pool_impl_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698