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

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

Issue 1708773002: TaskScheduler [7] SchedulerThreadPool (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@s_5_worker_thread
Patch Set: CR gab/danakj #25-26 Created 4 years, 8 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
(Empty)
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
3 // found in the LICENSE file.
4
5 #include "base/task_scheduler/scheduler_thread_pool.h"
6
7 #include <utility>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/task_scheduler/utils.h"
15 #include "base/threading/thread_local.h"
16
17 namespace base {
18 namespace internal {
19
20 namespace {
21
22 // Shared PriorityQueue of a thread's SchedulerThreadPool. Not set for threads
23 // that don't belong to a SchedulerThreadPool.
24 LazyInstance<ThreadLocalPointer<const PriorityQueue>>::Leaky
25 tls_current_shared_priority_queue = LAZY_INSTANCE_INITIALIZER;
26
27 // A task runner that runs tasks with the PARALLEL ExecutionMode.
28 class SchedulerParallelTaskRunner : public TaskRunner {
29 public:
30 SchedulerParallelTaskRunner(const TaskTraits& traits,
31 PriorityQueue* priority_queue,
32 TaskTracker* task_tracker)
33 : traits_(traits),
34 priority_queue_(priority_queue),
35 task_tracker_(task_tracker) {}
36
37 // TaskRunner:
38 bool PostDelayedTask(const tracked_objects::Location& from_here,
39 const Closure& closure,
40 TimeDelta delay) override {
41 // TODO(fdoray): Support delayed tasks.
42 DCHECK(delay.is_zero());
43
44 // Post the task as part of a one-off single-task Sequence.
45 return PostTaskHelper(WrapUnique(new Task(from_here, closure, traits_)),
46 make_scoped_refptr(new Sequence), priority_queue_,
47 task_tracker_);
48 }
49
50 bool RunsTasksOnCurrentThread() const override {
51 return tls_current_shared_priority_queue.Get().Get() == priority_queue_;
52 }
53
54 private:
55 ~SchedulerParallelTaskRunner() override = default;
56
57 const TaskTraits traits_;
58 PriorityQueue* const priority_queue_;
59 TaskTracker* const task_tracker_;
60
61 DISALLOW_COPY_AND_ASSIGN(SchedulerParallelTaskRunner);
62 };
63
64 } // namespace
65
66 class SchedulerThreadPool::SchedulerWorkerThreadDelegateImpl
67 : public SchedulerWorkerThread::Delegate {
68 public:
69 SchedulerWorkerThreadDelegateImpl(
70 SchedulerThreadPool* outer,
71 const EnqueueSequenceCallback enqueue_sequence_callback);
72 ~SchedulerWorkerThreadDelegateImpl() override;
73
74 // SchedulerWorkerThread::Delegate:
75 void OnMainEntry() override;
76 scoped_refptr<Sequence> GetWork(
77 SchedulerWorkerThread* worker_thread) override;
78 void EnqueueSequence(scoped_refptr<Sequence> sequence) override;
79
80 private:
81 SchedulerThreadPool* outer_;
82 const EnqueueSequenceCallback enqueue_sequence_callback_;
83
84 DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerThreadDelegateImpl);
85 };
86
87 std::unique_ptr<SchedulerThreadPool> SchedulerThreadPool::CreateThreadPool(
88 ThreadPriority thread_priority,
89 size_t max_threads,
90 const EnqueueSequenceCallback& enqueue_sequence_callback,
91 TaskTracker* task_tracker) {
92 std::unique_ptr<SchedulerThreadPool> thread_pool(
93 new SchedulerThreadPool(enqueue_sequence_callback, task_tracker));
94 if (thread_pool->Initialize(thread_priority, max_threads))
95 return thread_pool;
96 return nullptr;
97 }
98
99 SchedulerThreadPool::~SchedulerThreadPool() {
100 #if DCHECK_IS_ON()
101 // SchedulerThreadPool should never be deleted in production unless its
102 // initialization failed.
103 AutoSchedulerLock auto_lock(worker_threads_lock_);
104 DCHECK(join_for_testing_returned_.IsSignaled() || worker_threads_.empty());
105 #endif // DCHECK_IS_ON()
106 }
107
108 scoped_refptr<TaskRunner> SchedulerThreadPool::CreateTaskRunnerWithTraits(
109 const TaskTraits& traits,
110 ExecutionMode execution_mode) {
111 switch (execution_mode) {
112 case ExecutionMode::PARALLEL:
113 return make_scoped_refptr(new SchedulerParallelTaskRunner(
114 traits, &shared_priority_queue_, task_tracker_));
115
116 case ExecutionMode::SEQUENCED:
117 case ExecutionMode::SINGLE_THREADED:
118 // TODO(fdoray): Support SEQUENCED and SINGLE_THREADED TaskRunners.
119 NOTREACHED();
120 return nullptr;
121 }
122
123 NOTREACHED();
124 return nullptr;
125 }
126
127 void SchedulerThreadPool::EnqueueSequence(
128 scoped_refptr<Sequence> sequence,
129 const SequenceSortKey& sequence_sort_key) {
130 auto sequence_and_sort_key = WrapUnique(new PriorityQueue::SequenceAndSortKey(
131 std::move(sequence), sequence_sort_key));
132 auto transaction = shared_priority_queue_.BeginTransaction();
133
134 // The thread calling this method just ran a Task from |sequence| and will
135 // soon try to get another Sequence from which to run a Task. If the thread
136 // belongs to this pool, it will get that Sequence from
137 // |shared_priority_queue_|. When that's the case, there is no need to wake up
138 // another thread after |sequence| is inserted in |shared_priority_queue_|. If
139 // we did wake up another thread, we would waste resources by having more
140 // threads trying to get a Sequence from |shared_priority_queue_| than the
141 // number of Sequences in it.
142 if (tls_current_shared_priority_queue.Get().Get() == &shared_priority_queue_)
143 transaction->PushNoWakeUp(std::move(sequence_and_sort_key));
144 else
145 transaction->Push(std::move(sequence_and_sort_key));
146 }
147
148 void SchedulerThreadPool::WaitForAllWorkerThreadsIdleForTesting() {
149 AutoSchedulerLock auto_lock(worker_threads_lock_);
150 while (idle_worker_threads_stack_.size() < worker_threads_.size())
151 idle_worker_threads_stack_cv_for_testing_->Wait();
152 }
153
154 void SchedulerThreadPool::JoinForTesting() {
155 for (const auto& worker_thread : worker_threads_)
156 worker_thread->JoinForTesting();
157
158 DCHECK(!join_for_testing_returned_.IsSignaled());
159 join_for_testing_returned_.Signal();
160 }
161
162 SchedulerThreadPool::SchedulerWorkerThreadDelegateImpl::
163 SchedulerWorkerThreadDelegateImpl(
164 SchedulerThreadPool* outer,
165 const EnqueueSequenceCallback enqueue_sequence_callback)
166 : outer_(outer), enqueue_sequence_callback_(enqueue_sequence_callback) {}
167
168 SchedulerThreadPool::SchedulerWorkerThreadDelegateImpl::
169 ~SchedulerWorkerThreadDelegateImpl() = default;
170
171 void SchedulerThreadPool::SchedulerWorkerThreadDelegateImpl::OnMainEntry() {
172 DCHECK(!tls_current_shared_priority_queue.Get().Get());
173 tls_current_shared_priority_queue.Get().Set(&outer_->shared_priority_queue_);
174 }
175
176 scoped_refptr<Sequence>
177 SchedulerThreadPool::SchedulerWorkerThreadDelegateImpl::GetWork(
178 SchedulerWorkerThread* worker_thread) {
179 std::unique_ptr<PriorityQueue::Transaction> transaction(
180 outer_->shared_priority_queue_.BeginTransaction());
181 const auto sequence_and_sort_key = transaction->Peek();
182
183 if (sequence_and_sort_key.is_null()) {
184 // |transaction| is kept alive while |worker_thread| is added to
185 // |idle_worker_threads_stack_| to avoid this race:
186 // 1. This thread creates a Transaction, finds |shared_priority_queue_|
187 // empty and ends the Transaction.
188 // 2. Other thread creates a Transaction, inserts a Sequence into
189 // |shared_priority_queue_| and ends the Transaction. This can't happen
190 // if the Transaction of step 1 is still active because because there can
191 // only be one active Transaction per PriorityQueue at a time.
192 // 3. Other thread calls WakeUpOneThread(). No thread is woken up because
193 // |idle_worker_threads_stack_| is empty.
194 // 4. This thread adds itself to |idle_worker_threads_stack_| and goes to
195 // sleep. No thread runs the Sequence inserted in step 2.
196 outer_->AddToIdleWorkerThreadsStack(worker_thread);
197 return nullptr;
198 }
199
200 transaction->Pop();
201 return sequence_and_sort_key.sequence;
202 }
203
204 void SchedulerThreadPool::SchedulerWorkerThreadDelegateImpl::EnqueueSequence(
205 scoped_refptr<Sequence> sequence) {
206 enqueue_sequence_callback_.Run(std::move(sequence));
207 }
208
209 SchedulerThreadPool::SchedulerThreadPool(
210 const EnqueueSequenceCallback& enqueue_sequence_callback,
211 TaskTracker* task_tracker)
212 : shared_priority_queue_(
213 Bind(&SchedulerThreadPool::WakeUpOneThread, Unretained(this))),
214 worker_threads_lock_(shared_priority_queue_.container_lock()),
215 idle_worker_threads_stack_cv_for_testing_(
216 worker_threads_lock_.CreateConditionVariable()),
217 join_for_testing_returned_(true, false),
218 worker_thread_delegate_(
219 new SchedulerWorkerThreadDelegateImpl(this,
220 enqueue_sequence_callback)),
221 task_tracker_(task_tracker) {
222 DCHECK(task_tracker_);
223 }
224
225 bool SchedulerThreadPool::Initialize(ThreadPriority thread_priority,
226 size_t max_threads) {
227 AutoSchedulerLock auto_lock(worker_threads_lock_);
228
229 DCHECK(worker_threads_.empty());
230
231 for (size_t i = 0; i < max_threads; ++i) {
232 std::unique_ptr<SchedulerWorkerThread> worker_thread =
233 SchedulerWorkerThread::CreateSchedulerWorkerThread(
234 thread_priority, worker_thread_delegate_.get(), task_tracker_);
235 if (!worker_thread)
236 break;
237 idle_worker_threads_stack_.push(worker_thread.get());
238 worker_threads_.push_back(std::move(worker_thread));
239 }
240
241 return !worker_threads_.empty();
242 }
243
244 void SchedulerThreadPool::WakeUpOneThread() {
245 SchedulerWorkerThread* worker_thread;
246 {
247 AutoSchedulerLock auto_lock(worker_threads_lock_);
248
249 if (idle_worker_threads_stack_.empty())
250 return;
251
252 worker_thread = idle_worker_threads_stack_.top();
253 idle_worker_threads_stack_.pop();
254 }
255 worker_thread->WakeUp();
256 }
257
258 void SchedulerThreadPool::AddToIdleWorkerThreadsStack(
259 SchedulerWorkerThread* worker_thread) {
260 AutoSchedulerLock auto_lock(worker_threads_lock_);
261 idle_worker_threads_stack_.push(worker_thread);
262 DCHECK_LE(idle_worker_threads_stack_.size(), worker_threads_.size());
263
264 if (idle_worker_threads_stack_.size() == worker_threads_.size())
265 idle_worker_threads_stack_cv_for_testing_->Broadcast();
266 }
267
268 } // namespace internal
269 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698