blob: d9d2ea31a213ce4752bb7df941dd5710234b16f3 [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
Andreas Gampe9e927f52016-02-29 20:49:38 -080019#include <pthread.h>
20
21#include <sys/time.h>
22#include <sys/resource.h>
23
Vladimir Marko0b6e2832015-09-24 10:41:33 +010024#include "base/bit_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/casts.h"
Vladimir Marko0b6e2832015-09-24 10:41:33 +010026#include "base/logging.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010028#include "base/time_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "runtime.h"
Brian Carlstroma3d27182013-11-05 23:22:27 -080030#include "thread-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070032namespace art {
33
Mathieu Chartier720ef762013-08-17 14:46:54 -070034static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070035
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070036ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
37 size_t stack_size)
38 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080039 name_(name) {
Vladimir Marko0b6e2832015-09-24 10:41:33 +010040 // Add an inaccessible page to catch stack overflow.
41 stack_size += kPageSize;
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080042 std::string error_msg;
43 stack_.reset(MemMap::MapAnonymous(name.c_str(), nullptr, stack_size, PROT_READ | PROT_WRITE,
Vladimir Marko5c42c292015-02-25 12:02:49 +000044 false, false, &error_msg));
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080045 CHECK(stack_.get() != nullptr) << error_msg;
Vladimir Marko0b6e2832015-09-24 10:41:33 +010046 CHECK_ALIGNED(stack_->Begin(), kPageSize);
47 int mprotect_result = mprotect(stack_->Begin(), kPageSize, PROT_NONE);
48 CHECK_EQ(mprotect_result, 0) << "Failed to mprotect() bottom page of thread pool worker stack.";
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070049 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070050 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070051 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080052 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_->Begin(), stack_->Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070053 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
54 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
55}
56
57ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070058 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070059}
60
Andreas Gampe9e927f52016-02-29 20:49:38 -080061void ThreadPoolWorker::SetPthreadPriority(int priority) {
62 CHECK_GE(priority, PRIO_MIN);
63 CHECK_LE(priority, PRIO_MAX);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010064#if defined(ART_TARGET_ANDROID)
Andreas Gampe9e927f52016-02-29 20:49:38 -080065 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
66 if (result != 0) {
67 PLOG(ERROR) << "Failed to setpriority to :" << priority;
68 }
69#else
70 UNUSED(priority);
71#endif
72}
73
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070074void ThreadPoolWorker::Run() {
75 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070076 Task* task = nullptr;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080077 thread_pool_->creation_barier_.Wait(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070078 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070079 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070080 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070081 }
82}
83
84void* ThreadPoolWorker::Callback(void* arg) {
85 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
86 Runtime* runtime = Runtime::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070087 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(), true, nullptr, false));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +000088 worker->thread_ = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070089 // Do work until its time to shut down.
90 worker->Run();
91 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070092 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070093}
94
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070095void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070096 MutexLock mu(self, task_queue_lock_);
97 tasks_.push_back(task);
98 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070099 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700100 task_queue_condition_.Signal(self);
101 }
102}
103
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000104void ThreadPool::RemoveAllTasks(Thread* self) {
105 MutexLock mu(self, task_queue_lock_);
106 tasks_.clear();
107}
108
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800109ThreadPool::ThreadPool(const char* name, size_t num_threads)
110 : name_(name),
111 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700112 task_queue_condition_("task queue condition", task_queue_lock_),
113 completion_condition_("task completion condition", task_queue_lock_),
114 started_(false),
115 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800116 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -0700117 start_time_(0),
118 total_wait_time_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800119 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700120 creation_barier_(num_threads + 1),
121 max_active_workers_(num_threads) {
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800122 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700123 while (GetThreadCount() < num_threads) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800124 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
125 GetThreadCount());
Vladimir Marko0b6e2832015-09-24 10:41:33 +0100126 threads_.push_back(
127 new ThreadPoolWorker(this, worker_name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700128 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800129 // Wait for all of the threads to attach.
130 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700131}
132
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700133void ThreadPool::SetMaxActiveWorkers(size_t threads) {
134 MutexLock mu(Thread::Current(), task_queue_lock_);
135 CHECK_LE(threads, GetThreadCount());
136 max_active_workers_ = threads;
137}
138
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700139ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700140 {
141 Thread* self = Thread::Current();
142 MutexLock mu(self, task_queue_lock_);
143 // Tell any remaining workers to shut down.
144 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700145 // Broadcast to everyone waiting.
146 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700147 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700148 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700149 // Wait for the threads to finish.
150 STLDeleteElements(&threads_);
151}
152
153void ThreadPool::StartWorkers(Thread* self) {
154 MutexLock mu(self, task_queue_lock_);
155 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700156 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700157 start_time_ = NanoTime();
158 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700159}
160
161void ThreadPool::StopWorkers(Thread* self) {
162 MutexLock mu(self, task_queue_lock_);
163 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700164}
165
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700166Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700167 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700168 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700169 const size_t thread_count = GetThreadCount();
170 // Ensure that we don't use more threads than the maximum active workers.
171 const size_t active_threads = thread_count - waiting_count_;
172 // <= since self is considered an active worker.
173 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700174 Task* task = TryGetTaskLocked();
175 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700176 return task;
177 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700178 }
179
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700180 ++waiting_count_;
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800181 if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700182 // We may be done, lets broadcast to the completion condition.
183 completion_condition_.Broadcast(self);
184 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700185 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700186 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700187 if (kMeasureWaitTime) {
188 const uint64_t wait_end = NanoTime();
189 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
190 }
191 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700192 }
193
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700194 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700195 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700196}
197
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700198Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700199 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700200 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700201}
202
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700203Task* ThreadPool::TryGetTaskLocked() {
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800204 if (HasOutstandingTasks()) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700205 Task* task = tasks_.front();
206 tasks_.pop_front();
207 return task;
208 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700209 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700210}
211
Ian Rogers1d54e732013-05-02 21:10:01 -0700212void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
213 if (do_work) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700214 Task* task = nullptr;
215 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700216 task->Run(self);
217 task->Finalize();
218 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700219 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700220 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700221 MutexLock mu(self, task_queue_lock_);
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800222 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700223 if (!may_hold_locks) {
224 completion_condition_.Wait(self);
225 } else {
226 completion_condition_.WaitHoldingLocks(self);
227 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700228 }
229}
230
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700231size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700232 MutexLock mu(self, task_queue_lock_);
233 return tasks_.size();
234}
235
Andreas Gampe9e927f52016-02-29 20:49:38 -0800236void ThreadPool::SetPthreadPriority(int priority) {
237 for (ThreadPoolWorker* worker : threads_) {
238 worker->SetPthreadPriority(priority);
239 }
240}
241
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700242} // namespace art