blob: 39d30bb24d797ca0ecdea12f1d0588d27a0780d8 [file] [log] [blame]
Elliott Hughes1aa246d2012-12-13 09:29:36 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070017#include "thread_pool.h"
18
Elliott Hughes1aa246d2012-12-13 09:29:36 -080019#include "base/casts.h"
20#include "base/stl_util.h"
21#include "runtime.h"
22#include "thread.h"
23
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070024namespace art {
25
Mathieu Chartier720ef762013-08-17 14:46:54 -070026static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070027
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070028ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
29 size_t stack_size)
30 : thread_pool_(thread_pool),
31 name_(name),
32 stack_size_(stack_size) {
33 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070034 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070035 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
36 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), reason);
37 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
38 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
39}
40
41ThreadPoolWorker::~ThreadPoolWorker() {
42 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "thread pool worker shutdown");
43}
44
45void ThreadPoolWorker::Run() {
46 Thread* self = Thread::Current();
Mathieu Chartier02b6a782012-10-26 13:51:26 -070047 Task* task = NULL;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080048 thread_pool_->creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070049 while ((task = thread_pool_->GetTask(self)) != NULL) {
50 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070051 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070052 }
53}
54
55void* ThreadPoolWorker::Callback(void* arg) {
56 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
57 Runtime* runtime = Runtime::Current();
Mathieu Chartier664bebf2012-11-12 16:54:11 -080058 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(), true, NULL, false));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070059 // Do work until its time to shut down.
60 worker->Run();
61 runtime->DetachCurrentThread();
62 return NULL;
63}
64
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070065void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070066 MutexLock mu(self, task_queue_lock_);
67 tasks_.push_back(task);
68 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070069 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070070 task_queue_condition_.Signal(self);
71 }
72}
73
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070074ThreadPool::ThreadPool(size_t num_threads)
75 : task_queue_lock_("task queue lock"),
76 task_queue_condition_("task queue condition", task_queue_lock_),
77 completion_condition_("task completion condition", task_queue_lock_),
78 started_(false),
79 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080080 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -070081 start_time_(0),
82 total_wait_time_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080083 // Add one since the caller of constructor waits on the barrier too.
84 creation_barier_(num_threads + 1) {
85 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070086 while (GetThreadCount() < num_threads) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -070087 const std::string name = StringPrintf("Thread pool worker %zu", GetThreadCount());
88 threads_.push_back(new ThreadPoolWorker(this, name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070089 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -080090 // Wait for all of the threads to attach.
91 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070092}
93
94ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -070095 {
96 Thread* self = Thread::Current();
97 MutexLock mu(self, task_queue_lock_);
98 // Tell any remaining workers to shut down.
99 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700100 // Broadcast to everyone waiting.
101 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700102 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700103 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700104 // Wait for the threads to finish.
105 STLDeleteElements(&threads_);
106}
107
108void ThreadPool::StartWorkers(Thread* self) {
109 MutexLock mu(self, task_queue_lock_);
110 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700111 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700112 start_time_ = NanoTime();
113 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700114}
115
116void ThreadPool::StopWorkers(Thread* self) {
117 MutexLock mu(self, task_queue_lock_);
118 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700119}
120
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700121Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700122 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700123 while (!IsShuttingDown()) {
124 Task* task = TryGetTaskLocked(self);
125 if (task != NULL) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700126 return task;
127 }
128
129 waiting_count_++;
130 if (waiting_count_ == GetThreadCount() && tasks_.empty()) {
131 // We may be done, lets broadcast to the completion condition.
132 completion_condition_.Broadcast(self);
133 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700134 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700135 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700136 if (kMeasureWaitTime) {
137 const uint64_t wait_end = NanoTime();
138 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
139 }
140 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700141 }
142
143 // We are shutting down, return NULL to tell the worker thread to stop looping.
144 return NULL;
145}
146
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700147Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700148 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700149 return TryGetTaskLocked(self);
150}
151
152Task* ThreadPool::TryGetTaskLocked(Thread* self) {
153 if (started_ && !tasks_.empty()) {
154 Task* task = tasks_.front();
155 tasks_.pop_front();
156 return task;
157 }
158 return NULL;
159}
160
Ian Rogers1d54e732013-05-02 21:10:01 -0700161void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
162 if (do_work) {
163 Task* task = NULL;
164 while ((task = TryGetTask(self)) != NULL) {
165 task->Run(self);
166 task->Finalize();
167 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700168 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700169 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700170 MutexLock mu(self, task_queue_lock_);
171 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || !tasks_.empty())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700172 if (!may_hold_locks) {
173 completion_condition_.Wait(self);
174 } else {
175 completion_condition_.WaitHoldingLocks(self);
176 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700177 }
178}
179
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700180size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700181 MutexLock mu(self, task_queue_lock_);
182 return tasks_.size();
183}
184
185WorkStealingWorker::WorkStealingWorker(ThreadPool* thread_pool, const std::string& name,
186 size_t stack_size)
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -0700187 : ThreadPoolWorker(thread_pool, name, stack_size), task_(NULL) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700188
189void WorkStealingWorker::Run() {
190 Thread* self = Thread::Current();
191 Task* task = NULL;
192 WorkStealingThreadPool* thread_pool = down_cast<WorkStealingThreadPool*>(thread_pool_);
193 while ((task = thread_pool_->GetTask(self)) != NULL) {
194 WorkStealingTask* stealing_task = down_cast<WorkStealingTask*>(task);
195
196 {
197 CHECK(task_ == NULL);
198 MutexLock mu(self, thread_pool->work_steal_lock_);
199 // Register that we are running the task
200 ++stealing_task->ref_count_;
201 task_ = stealing_task;
202 }
203 stealing_task->Run(self);
204 // Mark ourselves as not running a task so that nobody tries to steal from us.
205 // There is a race condition that someone starts stealing from us at this point. This is okay
206 // due to the reference counting.
207 task_ = NULL;
208
209 bool finalize;
210
211 // Steal work from tasks until there is none left to steal. Note: There is a race, but
212 // all that happens when the race occurs is that we steal some work instead of processing a
213 // task from the queue.
214 while (thread_pool->GetTaskCount(self) == 0) {
215 WorkStealingTask* steal_from_task = NULL;
216
217 {
218 MutexLock mu(self, thread_pool->work_steal_lock_);
219 // Try finding a task to steal from.
220 steal_from_task = thread_pool->FindTaskToStealFrom(self);
221 if (steal_from_task != NULL) {
222 CHECK_NE(stealing_task, steal_from_task)
223 << "Attempting to steal from completed self task";
224 steal_from_task->ref_count_++;
225 } else {
226 break;
227 }
228 }
229
230 if (steal_from_task != NULL) {
231 // Task which completed earlier is going to steal some work.
232 stealing_task->StealFrom(self, steal_from_task);
233
234 {
235 // We are done stealing from the task, lets decrement its reference count.
236 MutexLock mu(self, thread_pool->work_steal_lock_);
237 finalize = !--steal_from_task->ref_count_;
238 }
239
240 if (finalize) {
241 steal_from_task->Finalize();
242 }
243 }
244 }
245
246 {
247 MutexLock mu(self, thread_pool->work_steal_lock_);
248 // If nobody is still referencing task_ we can finalize it.
249 finalize = !--stealing_task->ref_count_;
250 }
251
252 if (finalize) {
253 stealing_task->Finalize();
254 }
255 }
256}
257
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -0700258WorkStealingWorker::~WorkStealingWorker() {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700259
260WorkStealingThreadPool::WorkStealingThreadPool(size_t num_threads)
261 : ThreadPool(0),
262 work_steal_lock_("work stealing lock"),
263 steal_index_(0) {
264 while (GetThreadCount() < num_threads) {
265 const std::string name = StringPrintf("Work stealing worker %zu", GetThreadCount());
266 threads_.push_back(new WorkStealingWorker(this, name, ThreadPoolWorker::kDefaultStackSize));
267 }
268}
269
270WorkStealingTask* WorkStealingThreadPool::FindTaskToStealFrom(Thread* self) {
271 const size_t thread_count = GetThreadCount();
272 for (size_t i = 0; i < thread_count; ++i) {
273 // TODO: Use CAS instead of lock.
274 ++steal_index_;
275 if (steal_index_ >= thread_count) {
276 steal_index_-= thread_count;
277 }
278
279 WorkStealingWorker* worker = down_cast<WorkStealingWorker*>(threads_[steal_index_]);
280 WorkStealingTask* task = worker->task_;
281 if (task) {
282 // Not null, we can probably steal from this worker.
283 return task;
284 }
285 }
286 // Couldn't find something to steal.
287 return NULL;
288}
289
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -0700290WorkStealingThreadPool::~WorkStealingThreadPool() {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700291
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700292} // namespace art