blob: 1686ea63686acd2bedb606aeb91e16c3e752252b [file] [log] [blame]
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001#include "casts.h"
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07002#include "runtime.h"
3#include "stl_util.h"
4#include "thread.h"
5#include "thread_pool.h"
6
7namespace art {
8
9ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
10 size_t stack_size)
11 : thread_pool_(thread_pool),
12 name_(name),
13 stack_size_(stack_size) {
14 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070015 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070016 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
17 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), reason);
18 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
19 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
20}
21
22ThreadPoolWorker::~ThreadPoolWorker() {
23 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "thread pool worker shutdown");
24}
25
26void ThreadPoolWorker::Run() {
27 Thread* self = Thread::Current();
Mathieu Chartier02b6a782012-10-26 13:51:26 -070028 Task* task = NULL;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080029 thread_pool_->creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070030 while ((task = thread_pool_->GetTask(self)) != NULL) {
31 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070032 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070033 }
34}
35
36void* ThreadPoolWorker::Callback(void* arg) {
37 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
38 Runtime* runtime = Runtime::Current();
Mathieu Chartier664bebf2012-11-12 16:54:11 -080039 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(), true, NULL, false));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070040 // Do work until its time to shut down.
41 worker->Run();
42 runtime->DetachCurrentThread();
43 return NULL;
44}
45
Mathieu Chartier02b6a782012-10-26 13:51:26 -070046void ThreadPool::AddTask(Thread* self, Task* task){
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070047 MutexLock mu(self, task_queue_lock_);
48 tasks_.push_back(task);
49 // If we have any waiters, signal one.
50 if (waiting_count_ != 0) {
51 task_queue_condition_.Signal(self);
52 }
53}
54
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070055ThreadPool::ThreadPool(size_t num_threads)
56 : task_queue_lock_("task queue lock"),
57 task_queue_condition_("task queue condition", task_queue_lock_),
58 completion_condition_("task completion condition", task_queue_lock_),
59 started_(false),
60 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080061 waiting_count_(0),
62 // Add one since the caller of constructor waits on the barrier too.
63 creation_barier_(num_threads + 1) {
64 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070065 while (GetThreadCount() < num_threads) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -070066 const std::string name = StringPrintf("Thread pool worker %zu", GetThreadCount());
67 threads_.push_back(new ThreadPoolWorker(this, name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070068 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -080069 // Wait for all of the threads to attach.
70 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070071}
72
73ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -070074 {
75 Thread* self = Thread::Current();
76 MutexLock mu(self, task_queue_lock_);
77 // Tell any remaining workers to shut down.
78 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -070079 // Broadcast to everyone waiting.
80 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070081 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -070082 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070083 // Wait for the threads to finish.
84 STLDeleteElements(&threads_);
85}
86
87void ThreadPool::StartWorkers(Thread* self) {
88 MutexLock mu(self, task_queue_lock_);
89 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070090 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070091 start_time_ = NanoTime();
92 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070093}
94
95void ThreadPool::StopWorkers(Thread* self) {
96 MutexLock mu(self, task_queue_lock_);
97 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070098}
99
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700100Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700101 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700102 while (!IsShuttingDown()) {
103 Task* task = TryGetTaskLocked(self);
104 if (task != NULL) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700105 return task;
106 }
107
108 waiting_count_++;
109 if (waiting_count_ == GetThreadCount() && tasks_.empty()) {
110 // We may be done, lets broadcast to the completion condition.
111 completion_condition_.Broadcast(self);
112 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700113 const uint64_t wait_start = NanoTime();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700114 task_queue_condition_.Wait(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700115 const uint64_t wait_end = NanoTime();
116 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700117 waiting_count_--;
118 }
119
120 // We are shutting down, return NULL to tell the worker thread to stop looping.
121 return NULL;
122}
123
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700124Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700125 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700126 return TryGetTaskLocked(self);
127}
128
129Task* ThreadPool::TryGetTaskLocked(Thread* self) {
130 if (started_ && !tasks_.empty()) {
131 Task* task = tasks_.front();
132 tasks_.pop_front();
133 return task;
134 }
135 return NULL;
136}
137
138void ThreadPool::Wait(Thread* self, bool do_work) {
139 Task* task = NULL;
140 while ((task = TryGetTask(self)) != NULL) {
141 task->Run(self);
142 task->Finalize();
143 }
144
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700145 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700146 MutexLock mu(self, task_queue_lock_);
147 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || !tasks_.empty())) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700148 completion_condition_.Wait(self);
149 }
150}
151
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700152size_t ThreadPool::GetTaskCount(Thread* self){
153 MutexLock mu(self, task_queue_lock_);
154 return tasks_.size();
155}
156
157WorkStealingWorker::WorkStealingWorker(ThreadPool* thread_pool, const std::string& name,
158 size_t stack_size)
159 : ThreadPoolWorker(thread_pool, name, stack_size),
160 task_(NULL) {
161
162}
163
164void WorkStealingWorker::Run() {
165 Thread* self = Thread::Current();
166 Task* task = NULL;
167 WorkStealingThreadPool* thread_pool = down_cast<WorkStealingThreadPool*>(thread_pool_);
168 while ((task = thread_pool_->GetTask(self)) != NULL) {
169 WorkStealingTask* stealing_task = down_cast<WorkStealingTask*>(task);
170
171 {
172 CHECK(task_ == NULL);
173 MutexLock mu(self, thread_pool->work_steal_lock_);
174 // Register that we are running the task
175 ++stealing_task->ref_count_;
176 task_ = stealing_task;
177 }
178 stealing_task->Run(self);
179 // Mark ourselves as not running a task so that nobody tries to steal from us.
180 // There is a race condition that someone starts stealing from us at this point. This is okay
181 // due to the reference counting.
182 task_ = NULL;
183
184 bool finalize;
185
186 // Steal work from tasks until there is none left to steal. Note: There is a race, but
187 // all that happens when the race occurs is that we steal some work instead of processing a
188 // task from the queue.
189 while (thread_pool->GetTaskCount(self) == 0) {
190 WorkStealingTask* steal_from_task = NULL;
191
192 {
193 MutexLock mu(self, thread_pool->work_steal_lock_);
194 // Try finding a task to steal from.
195 steal_from_task = thread_pool->FindTaskToStealFrom(self);
196 if (steal_from_task != NULL) {
197 CHECK_NE(stealing_task, steal_from_task)
198 << "Attempting to steal from completed self task";
199 steal_from_task->ref_count_++;
200 } else {
201 break;
202 }
203 }
204
205 if (steal_from_task != NULL) {
206 // Task which completed earlier is going to steal some work.
207 stealing_task->StealFrom(self, steal_from_task);
208
209 {
210 // We are done stealing from the task, lets decrement its reference count.
211 MutexLock mu(self, thread_pool->work_steal_lock_);
212 finalize = !--steal_from_task->ref_count_;
213 }
214
215 if (finalize) {
216 steal_from_task->Finalize();
217 }
218 }
219 }
220
221 {
222 MutexLock mu(self, thread_pool->work_steal_lock_);
223 // If nobody is still referencing task_ we can finalize it.
224 finalize = !--stealing_task->ref_count_;
225 }
226
227 if (finalize) {
228 stealing_task->Finalize();
229 }
230 }
231}
232
233WorkStealingWorker::~WorkStealingWorker() {
234
235}
236
237WorkStealingThreadPool::WorkStealingThreadPool(size_t num_threads)
238 : ThreadPool(0),
239 work_steal_lock_("work stealing lock"),
240 steal_index_(0) {
241 while (GetThreadCount() < num_threads) {
242 const std::string name = StringPrintf("Work stealing worker %zu", GetThreadCount());
243 threads_.push_back(new WorkStealingWorker(this, name, ThreadPoolWorker::kDefaultStackSize));
244 }
245}
246
247WorkStealingTask* WorkStealingThreadPool::FindTaskToStealFrom(Thread* self) {
248 const size_t thread_count = GetThreadCount();
249 for (size_t i = 0; i < thread_count; ++i) {
250 // TODO: Use CAS instead of lock.
251 ++steal_index_;
252 if (steal_index_ >= thread_count) {
253 steal_index_-= thread_count;
254 }
255
256 WorkStealingWorker* worker = down_cast<WorkStealingWorker*>(threads_[steal_index_]);
257 WorkStealingTask* task = worker->task_;
258 if (task) {
259 // Not null, we can probably steal from this worker.
260 return task;
261 }
262 }
263 // Couldn't find something to steal.
264 return NULL;
265}
266
267WorkStealingThreadPool::~WorkStealingThreadPool() {
268
269}
270
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700271} // namespace art