blob: 365c09757855be9fcd580feefd25ae295e44cbb3 [file] [log] [blame]
Mathieu Chartier93c21ba2018-12-10 13:08:30 -08001
Elliott Hughes1aa246d2012-12-13 09:29:36 -08002/*
3 * Copyright (C) 2012 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070018#include "thread_pool.h"
19
Andreas Gamped4901292017-05-30 18:41:34 -070020#include <sys/mman.h>
Andreas Gampe9e927f52016-02-29 20:49:38 -080021#include <sys/resource.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070022#include <sys/time.h>
23
24#include <pthread.h>
Andreas Gampe9e927f52016-02-29 20:49:38 -080025
Andreas Gampe57943812017-12-06 21:39:13 -080026#include <android-base/logging.h>
27#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080028
Vladimir Marko0b6e2832015-09-24 10:41:33 +010029#include "base/bit_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/casts.h"
31#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010032#include "base/time_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080033#include "base/utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080034#include "runtime.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070035#include "thread-current-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080036
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070037namespace art {
38
Andreas Gampe46ee31b2016-12-14 10:11:49 -080039using android::base::StringPrintf;
40
Mathieu Chartier720ef762013-08-17 14:46:54 -070041static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070042
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070043ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
44 size_t stack_size)
45 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080046 name_(name) {
Vladimir Marko0b6e2832015-09-24 10:41:33 +010047 // Add an inaccessible page to catch stack overflow.
48 stack_size += kPageSize;
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080049 std::string error_msg;
Vladimir Markoc34bebf2018-08-16 16:12:49 +010050 stack_ = MemMap::MapAnonymous(name.c_str(),
Vladimir Markoc34bebf2018-08-16 16:12:49 +010051 stack_size,
52 PROT_READ | PROT_WRITE,
Vladimir Marko11306592018-10-26 14:22:59 +010053 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +010054 &error_msg);
55 CHECK(stack_.IsValid()) << error_msg;
56 CHECK_ALIGNED(stack_.Begin(), kPageSize);
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -070057 CheckedCall(mprotect,
58 "mprotect bottom page of thread pool worker stack",
Vladimir Markoc34bebf2018-08-16 16:12:49 +010059 stack_.Begin(),
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -070060 kPageSize,
61 PROT_NONE);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070062 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070063 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070064 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010065 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_.Begin(), stack_.Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070066 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
67 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
68}
69
70ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070071 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070072}
73
Andreas Gampe9e927f52016-02-29 20:49:38 -080074void ThreadPoolWorker::SetPthreadPriority(int priority) {
75 CHECK_GE(priority, PRIO_MIN);
76 CHECK_LE(priority, PRIO_MAX);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010077#if defined(ART_TARGET_ANDROID)
Andreas Gampe9e927f52016-02-29 20:49:38 -080078 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
79 if (result != 0) {
80 PLOG(ERROR) << "Failed to setpriority to :" << priority;
81 }
82#else
83 UNUSED(priority);
84#endif
85}
86
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070087void ThreadPoolWorker::Run() {
88 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070089 Task* task = nullptr;
Mathieu Chartier93c21ba2018-12-10 13:08:30 -080090 thread_pool_->creation_barier_.Pass(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070091 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070092 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070093 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070094 }
95}
96
97void* ThreadPoolWorker::Callback(void* arg) {
98 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
99 Runtime* runtime = Runtime::Current();
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800100 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(),
101 true,
102 nullptr,
103 worker->thread_pool_->create_peers_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +0000104 worker->thread_ = Thread::Current();
Alex Lighte9f61032018-09-24 16:04:51 -0700105 // Mark thread pool workers as runtime-threads.
106 worker->thread_->SetIsRuntimeThread(true);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700107 // Do work until its time to shut down.
108 worker->Run();
109 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700110 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700111}
112
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700113void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700114 MutexLock mu(self, task_queue_lock_);
115 tasks_.push_back(task);
116 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700117 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700118 task_queue_condition_.Signal(self);
119 }
120}
121
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000122void ThreadPool::RemoveAllTasks(Thread* self) {
Nicolas Geoffray714fad62019-06-27 15:32:00 +0100123 // The ThreadPool is responsible for calling Finalize (which usually delete
124 // the task memory) on all the tasks.
125 Task* task = nullptr;
126 while ((task = TryGetTask(self)) != nullptr) {
127 task->Finalize();
128 }
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000129 MutexLock mu(self, task_queue_lock_);
130 tasks_.clear();
131}
132
Mathieu Chartiereac4d6a2018-12-05 12:33:46 -0800133ThreadPool::ThreadPool(const char* name,
134 size_t num_threads,
135 bool create_peers,
136 size_t worker_stack_size)
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800137 : name_(name),
138 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700139 task_queue_condition_("task queue condition", task_queue_lock_),
140 completion_condition_("task completion condition", task_queue_lock_),
141 started_(false),
142 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800143 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -0700144 start_time_(0),
145 total_wait_time_(0),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000146 creation_barier_(0),
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800147 max_active_workers_(num_threads),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000148 create_peers_(create_peers),
149 worker_stack_size_(worker_stack_size) {
150 CreateThreads();
151}
152
153void ThreadPool::CreateThreads() {
154 CHECK(threads_.empty());
155 Thread* self = Thread::Current();
156 {
157 MutexLock mu(self, task_queue_lock_);
158 shutting_down_ = false;
159 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800160 creation_barier_.Init(self, max_active_workers_);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000161 while (GetThreadCount() < max_active_workers_) {
162 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
163 GetThreadCount());
164 threads_.push_back(
165 new ThreadPoolWorker(this, worker_name, worker_stack_size_));
166 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700167 }
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800168}
169
170void ThreadPool::WaitForWorkersToBeCreated() {
171 creation_barier_.Increment(Thread::Current(), 0);
172}
173
174const std::vector<ThreadPoolWorker*>& ThreadPool::GetWorkers() {
175 // Wait for all the workers to be created before returning them.
176 WaitForWorkersToBeCreated();
177 return threads_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700178}
179
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000180void ThreadPool::DeleteThreads() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700181 {
182 Thread* self = Thread::Current();
183 MutexLock mu(self, task_queue_lock_);
184 // Tell any remaining workers to shut down.
185 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700186 // Broadcast to everyone waiting.
187 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700188 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700189 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000190 // Wait for the threads to finish. We expect the user of the pool
191 // not to run multi-threaded calls to `CreateThreads` and `DeleteThreads`,
192 // so we don't guard the field here.
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700193 STLDeleteElements(&threads_);
194}
195
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000196void ThreadPool::SetMaxActiveWorkers(size_t max_workers) {
197 MutexLock mu(Thread::Current(), task_queue_lock_);
198 CHECK_LE(max_workers, GetThreadCount());
199 max_active_workers_ = max_workers;
200}
201
202ThreadPool::~ThreadPool() {
203 DeleteThreads();
Nicolas Geoffray714fad62019-06-27 15:32:00 +0100204 RemoveAllTasks(Thread::Current());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000205}
206
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700207void ThreadPool::StartWorkers(Thread* self) {
208 MutexLock mu(self, task_queue_lock_);
209 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700210 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700211 start_time_ = NanoTime();
212 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700213}
214
215void ThreadPool::StopWorkers(Thread* self) {
216 MutexLock mu(self, task_queue_lock_);
217 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700218}
219
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700220Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700221 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700222 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700223 const size_t thread_count = GetThreadCount();
224 // Ensure that we don't use more threads than the maximum active workers.
225 const size_t active_threads = thread_count - waiting_count_;
226 // <= since self is considered an active worker.
227 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700228 Task* task = TryGetTaskLocked();
229 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700230 return task;
231 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700232 }
233
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700234 ++waiting_count_;
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800235 if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700236 // We may be done, lets broadcast to the completion condition.
237 completion_condition_.Broadcast(self);
238 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700239 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700240 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700241 if (kMeasureWaitTime) {
242 const uint64_t wait_end = NanoTime();
243 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
244 }
245 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700246 }
247
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700248 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700249 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700250}
251
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700252Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700253 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700254 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700255}
256
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700257Task* ThreadPool::TryGetTaskLocked() {
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800258 if (HasOutstandingTasks()) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700259 Task* task = tasks_.front();
260 tasks_.pop_front();
261 return task;
262 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700263 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700264}
265
Ian Rogers1d54e732013-05-02 21:10:01 -0700266void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
267 if (do_work) {
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800268 CHECK(!create_peers_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700269 Task* task = nullptr;
270 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700271 task->Run(self);
272 task->Finalize();
273 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700274 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700275 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700276 MutexLock mu(self, task_queue_lock_);
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800277 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700278 if (!may_hold_locks) {
279 completion_condition_.Wait(self);
280 } else {
281 completion_condition_.WaitHoldingLocks(self);
282 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700283 }
284}
285
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700286size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700287 MutexLock mu(self, task_queue_lock_);
288 return tasks_.size();
289}
290
Andreas Gampe9e927f52016-02-29 20:49:38 -0800291void ThreadPool::SetPthreadPriority(int priority) {
292 for (ThreadPoolWorker* worker : threads_) {
293 worker->SetPthreadPriority(priority);
294 }
295}
296
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700297} // namespace art