blob: de698c269f9d5b312c70cc70bbc128281232cdc1 [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 Gamped4901292017-05-30 18:41:34 -070019#include <sys/mman.h>
Andreas Gampe9e927f52016-02-29 20:49:38 -080020#include <sys/resource.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include <sys/time.h>
22
23#include <pthread.h>
Andreas Gampe9e927f52016-02-29 20:49:38 -080024
Andreas Gampe57943812017-12-06 21:39:13 -080025#include <android-base/logging.h>
26#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080027
Vladimir Marko0b6e2832015-09-24 10:41:33 +010028#include "base/bit_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/casts.h"
30#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080032#include "base/utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080033#include "runtime.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070034#include "thread-current-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080035
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070036namespace art {
37
Andreas Gampe46ee31b2016-12-14 10:11:49 -080038using android::base::StringPrintf;
39
Mathieu Chartier720ef762013-08-17 14:46:54 -070040static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070041
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070042ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
43 size_t stack_size)
44 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080045 name_(name) {
Vladimir Marko0b6e2832015-09-24 10:41:33 +010046 // Add an inaccessible page to catch stack overflow.
47 stack_size += kPageSize;
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080048 std::string error_msg;
Vladimir Markoc34bebf2018-08-16 16:12:49 +010049 stack_ = MemMap::MapAnonymous(name.c_str(),
Vladimir Markoc34bebf2018-08-16 16:12:49 +010050 stack_size,
51 PROT_READ | PROT_WRITE,
Vladimir Marko11306592018-10-26 14:22:59 +010052 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +010053 &error_msg);
54 CHECK(stack_.IsValid()) << error_msg;
55 CHECK_ALIGNED(stack_.Begin(), kPageSize);
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -070056 CheckedCall(mprotect,
57 "mprotect bottom page of thread pool worker stack",
Vladimir Markoc34bebf2018-08-16 16:12:49 +010058 stack_.Begin(),
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -070059 kPageSize,
60 PROT_NONE);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070061 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070062 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070063 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010064 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_.Begin(), stack_.Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070065 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
66 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
67}
68
69ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070070 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070071}
72
Andreas Gampe9e927f52016-02-29 20:49:38 -080073void ThreadPoolWorker::SetPthreadPriority(int priority) {
74 CHECK_GE(priority, PRIO_MIN);
75 CHECK_LE(priority, PRIO_MAX);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010076#if defined(ART_TARGET_ANDROID)
Andreas Gampe9e927f52016-02-29 20:49:38 -080077 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
78 if (result != 0) {
79 PLOG(ERROR) << "Failed to setpriority to :" << priority;
80 }
81#else
82 UNUSED(priority);
83#endif
84}
85
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070086void ThreadPoolWorker::Run() {
87 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070088 Task* task = nullptr;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080089 thread_pool_->creation_barier_.Wait(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070090 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070091 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070092 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070093 }
94}
95
96void* ThreadPoolWorker::Callback(void* arg) {
97 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
98 Runtime* runtime = Runtime::Current();
Andreas Gampeb15de0c2017-01-24 13:12:19 -080099 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(),
100 true,
101 nullptr,
102 worker->thread_pool_->create_peers_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +0000103 worker->thread_ = Thread::Current();
Alex Lighte9f61032018-09-24 16:04:51 -0700104 // Mark thread pool workers as runtime-threads.
105 worker->thread_->SetIsRuntimeThread(true);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700106 // Do work until its time to shut down.
107 worker->Run();
108 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700109 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700110}
111
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700112void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700113 MutexLock mu(self, task_queue_lock_);
114 tasks_.push_back(task);
115 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700116 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700117 task_queue_condition_.Signal(self);
118 }
119}
120
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000121void ThreadPool::RemoveAllTasks(Thread* self) {
122 MutexLock mu(self, task_queue_lock_);
123 tasks_.clear();
124}
125
Mathieu Chartiereac4d6a2018-12-05 12:33:46 -0800126ThreadPool::ThreadPool(const char* name,
127 size_t num_threads,
128 bool create_peers,
129 size_t worker_stack_size)
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800130 : name_(name),
131 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700132 task_queue_condition_("task queue condition", task_queue_lock_),
133 completion_condition_("task completion condition", task_queue_lock_),
134 started_(false),
135 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800136 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -0700137 start_time_(0),
138 total_wait_time_(0),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000139 creation_barier_(0),
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800140 max_active_workers_(num_threads),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000141 create_peers_(create_peers),
142 worker_stack_size_(worker_stack_size) {
143 CreateThreads();
144}
145
146void ThreadPool::CreateThreads() {
147 CHECK(threads_.empty());
148 Thread* self = Thread::Current();
149 {
150 MutexLock mu(self, task_queue_lock_);
151 shutting_down_ = false;
152 // Add one since the caller of constructor waits on the barrier too.
153 creation_barier_.Init(self, max_active_workers_ + 1);
154 while (GetThreadCount() < max_active_workers_) {
155 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
156 GetThreadCount());
157 threads_.push_back(
158 new ThreadPoolWorker(this, worker_name, worker_stack_size_));
159 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700160 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800161 // Wait for all of the threads to attach.
Mathieu Chartiereac4d6a2018-12-05 12:33:46 -0800162 creation_barier_.Wait(Thread::Current());
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700163}
164
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000165void ThreadPool::DeleteThreads() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700166 {
167 Thread* self = Thread::Current();
168 MutexLock mu(self, task_queue_lock_);
169 // Tell any remaining workers to shut down.
170 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700171 // Broadcast to everyone waiting.
172 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700173 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700174 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000175 // Wait for the threads to finish. We expect the user of the pool
176 // not to run multi-threaded calls to `CreateThreads` and `DeleteThreads`,
177 // so we don't guard the field here.
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700178 STLDeleteElements(&threads_);
179}
180
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000181void ThreadPool::SetMaxActiveWorkers(size_t max_workers) {
182 MutexLock mu(Thread::Current(), task_queue_lock_);
183 CHECK_LE(max_workers, GetThreadCount());
184 max_active_workers_ = max_workers;
185}
186
187ThreadPool::~ThreadPool() {
188 DeleteThreads();
189}
190
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700191void ThreadPool::StartWorkers(Thread* self) {
192 MutexLock mu(self, task_queue_lock_);
193 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700194 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700195 start_time_ = NanoTime();
196 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700197}
198
199void ThreadPool::StopWorkers(Thread* self) {
200 MutexLock mu(self, task_queue_lock_);
201 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700202}
203
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700204Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700205 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700206 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700207 const size_t thread_count = GetThreadCount();
208 // Ensure that we don't use more threads than the maximum active workers.
209 const size_t active_threads = thread_count - waiting_count_;
210 // <= since self is considered an active worker.
211 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700212 Task* task = TryGetTaskLocked();
213 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700214 return task;
215 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700216 }
217
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700218 ++waiting_count_;
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800219 if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700220 // We may be done, lets broadcast to the completion condition.
221 completion_condition_.Broadcast(self);
222 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700223 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700224 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700225 if (kMeasureWaitTime) {
226 const uint64_t wait_end = NanoTime();
227 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
228 }
229 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700230 }
231
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700232 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700233 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700234}
235
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700236Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700237 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700238 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700239}
240
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700241Task* ThreadPool::TryGetTaskLocked() {
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800242 if (HasOutstandingTasks()) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700243 Task* task = tasks_.front();
244 tasks_.pop_front();
245 return task;
246 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700247 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700248}
249
Ian Rogers1d54e732013-05-02 21:10:01 -0700250void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
251 if (do_work) {
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800252 CHECK(!create_peers_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700253 Task* task = nullptr;
254 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700255 task->Run(self);
256 task->Finalize();
257 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700258 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700259 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700260 MutexLock mu(self, task_queue_lock_);
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800261 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 if (!may_hold_locks) {
263 completion_condition_.Wait(self);
264 } else {
265 completion_condition_.WaitHoldingLocks(self);
266 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700267 }
268}
269
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700270size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700271 MutexLock mu(self, task_queue_lock_);
272 return tasks_.size();
273}
274
Andreas Gampe9e927f52016-02-29 20:49:38 -0800275void ThreadPool::SetPthreadPriority(int priority) {
276 for (ThreadPoolWorker* worker : threads_) {
277 worker->SetPthreadPriority(priority);
278 }
279}
280
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700281} // namespace art