blob: 0dc3a8fed742ccf256e4f1437064c57167493762 [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
Daniel Colascione034ac512020-03-18 19:06:11 -070043#if defined(__BIONIC__)
44static constexpr bool kUseCustomThreadPoolStack = false;
45#else
46static constexpr bool kUseCustomThreadPoolStack = true;
47#endif
48
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070049ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
50 size_t stack_size)
51 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080052 name_(name) {
53 std::string error_msg;
Daniel Colascione034ac512020-03-18 19:06:11 -070054 // On Bionic, we know pthreads will give us a big-enough stack with
55 // a guard page, so don't do anything special on Bionic libc.
56 if (kUseCustomThreadPoolStack) {
57 // Add an inaccessible page to catch stack overflow.
58 stack_size += kPageSize;
59 stack_ = MemMap::MapAnonymous(name.c_str(),
60 stack_size,
61 PROT_READ | PROT_WRITE,
62 /*low_4gb=*/ false,
63 &error_msg);
64 CHECK(stack_.IsValid()) << error_msg;
65 CHECK_ALIGNED(stack_.Begin(), kPageSize);
66 CheckedCall(mprotect,
67 "mprotect bottom page of thread pool worker stack",
68 stack_.Begin(),
69 kPageSize,
70 PROT_NONE);
71 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070072 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070073 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070074 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Daniel Colascione034ac512020-03-18 19:06:11 -070075 if (kUseCustomThreadPoolStack) {
76 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_.Begin(), stack_.Size()), reason);
77 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070078 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
79 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
80}
81
82ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070083 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070084}
85
Andreas Gampe9e927f52016-02-29 20:49:38 -080086void ThreadPoolWorker::SetPthreadPriority(int priority) {
87 CHECK_GE(priority, PRIO_MIN);
88 CHECK_LE(priority, PRIO_MAX);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010089#if defined(ART_TARGET_ANDROID)
Andreas Gampe9e927f52016-02-29 20:49:38 -080090 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
91 if (result != 0) {
92 PLOG(ERROR) << "Failed to setpriority to :" << priority;
93 }
94#else
95 UNUSED(priority);
96#endif
97}
98
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070099void ThreadPoolWorker::Run() {
100 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700101 Task* task = nullptr;
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800102 thread_pool_->creation_barier_.Pass(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700103 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700104 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700105 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700106 }
107}
108
109void* ThreadPoolWorker::Callback(void* arg) {
110 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
111 Runtime* runtime = Runtime::Current();
Alex Light80777ed2019-12-17 17:07:33 +0000112 CHECK(runtime->AttachCurrentThread(
113 worker->name_.c_str(),
114 true,
115 // Thread-groups are only tracked by the peer j.l.Thread objects. If we aren't creating peers
116 // we don't need to specify the thread group. We want to place these threads in the System
117 // thread group because that thread group is where important threads that debuggers and
118 // similar tools should not mess with are placed. As this is an internal-thread-pool we might
119 // rely on being able to (for example) wait for all threads to finish some task. If debuggers
120 // are suspending these threads that might not be possible.
121 worker->thread_pool_->create_peers_ ? runtime->GetSystemThreadGroup() : nullptr,
122 worker->thread_pool_->create_peers_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +0000123 worker->thread_ = Thread::Current();
Alex Lighte9f61032018-09-24 16:04:51 -0700124 // Mark thread pool workers as runtime-threads.
125 worker->thread_->SetIsRuntimeThread(true);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700126 // Do work until its time to shut down.
127 worker->Run();
128 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700129 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700130}
131
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700132void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700133 MutexLock mu(self, task_queue_lock_);
134 tasks_.push_back(task);
135 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700136 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700137 task_queue_condition_.Signal(self);
138 }
139}
140
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000141void ThreadPool::RemoveAllTasks(Thread* self) {
Nicolas Geoffray714fad62019-06-27 15:32:00 +0100142 // The ThreadPool is responsible for calling Finalize (which usually delete
143 // the task memory) on all the tasks.
144 Task* task = nullptr;
145 while ((task = TryGetTask(self)) != nullptr) {
146 task->Finalize();
147 }
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000148 MutexLock mu(self, task_queue_lock_);
149 tasks_.clear();
150}
151
Mathieu Chartiereac4d6a2018-12-05 12:33:46 -0800152ThreadPool::ThreadPool(const char* name,
153 size_t num_threads,
154 bool create_peers,
155 size_t worker_stack_size)
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800156 : name_(name),
157 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700158 task_queue_condition_("task queue condition", task_queue_lock_),
159 completion_condition_("task completion condition", task_queue_lock_),
160 started_(false),
161 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800162 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -0700163 start_time_(0),
164 total_wait_time_(0),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000165 creation_barier_(0),
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800166 max_active_workers_(num_threads),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000167 create_peers_(create_peers),
168 worker_stack_size_(worker_stack_size) {
169 CreateThreads();
170}
171
172void ThreadPool::CreateThreads() {
173 CHECK(threads_.empty());
174 Thread* self = Thread::Current();
175 {
176 MutexLock mu(self, task_queue_lock_);
177 shutting_down_ = false;
178 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800179 creation_barier_.Init(self, max_active_workers_);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000180 while (GetThreadCount() < max_active_workers_) {
181 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
182 GetThreadCount());
183 threads_.push_back(
184 new ThreadPoolWorker(this, worker_name, worker_stack_size_));
185 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700186 }
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800187}
188
189void ThreadPool::WaitForWorkersToBeCreated() {
190 creation_barier_.Increment(Thread::Current(), 0);
191}
192
193const std::vector<ThreadPoolWorker*>& ThreadPool::GetWorkers() {
194 // Wait for all the workers to be created before returning them.
195 WaitForWorkersToBeCreated();
196 return threads_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700197}
198
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000199void ThreadPool::DeleteThreads() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700200 {
201 Thread* self = Thread::Current();
202 MutexLock mu(self, task_queue_lock_);
203 // Tell any remaining workers to shut down.
204 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700205 // Broadcast to everyone waiting.
206 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700207 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700208 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000209 // Wait for the threads to finish. We expect the user of the pool
210 // not to run multi-threaded calls to `CreateThreads` and `DeleteThreads`,
211 // so we don't guard the field here.
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700212 STLDeleteElements(&threads_);
213}
214
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000215void ThreadPool::SetMaxActiveWorkers(size_t max_workers) {
216 MutexLock mu(Thread::Current(), task_queue_lock_);
217 CHECK_LE(max_workers, GetThreadCount());
218 max_active_workers_ = max_workers;
219}
220
221ThreadPool::~ThreadPool() {
222 DeleteThreads();
Nicolas Geoffray714fad62019-06-27 15:32:00 +0100223 RemoveAllTasks(Thread::Current());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000224}
225
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700226void ThreadPool::StartWorkers(Thread* self) {
227 MutexLock mu(self, task_queue_lock_);
228 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700229 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700230 start_time_ = NanoTime();
231 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700232}
233
234void ThreadPool::StopWorkers(Thread* self) {
235 MutexLock mu(self, task_queue_lock_);
236 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700237}
238
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700239Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700240 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700241 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700242 const size_t thread_count = GetThreadCount();
243 // Ensure that we don't use more threads than the maximum active workers.
244 const size_t active_threads = thread_count - waiting_count_;
245 // <= since self is considered an active worker.
246 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700247 Task* task = TryGetTaskLocked();
248 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700249 return task;
250 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700251 }
252
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700253 ++waiting_count_;
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800254 if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700255 // We may be done, lets broadcast to the completion condition.
256 completion_condition_.Broadcast(self);
257 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700258 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700259 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700260 if (kMeasureWaitTime) {
261 const uint64_t wait_end = NanoTime();
262 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
263 }
264 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700265 }
266
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700267 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700268 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700269}
270
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700271Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700272 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700273 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700274}
275
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700276Task* ThreadPool::TryGetTaskLocked() {
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800277 if (HasOutstandingTasks()) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700278 Task* task = tasks_.front();
279 tasks_.pop_front();
280 return task;
281 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700282 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700283}
284
Ian Rogers1d54e732013-05-02 21:10:01 -0700285void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
286 if (do_work) {
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800287 CHECK(!create_peers_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700288 Task* task = nullptr;
289 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700290 task->Run(self);
291 task->Finalize();
292 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700293 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700294 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700295 MutexLock mu(self, task_queue_lock_);
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800296 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700297 if (!may_hold_locks) {
298 completion_condition_.Wait(self);
299 } else {
300 completion_condition_.WaitHoldingLocks(self);
301 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700302 }
303}
304
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700305size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700306 MutexLock mu(self, task_queue_lock_);
307 return tasks_.size();
308}
309
Andreas Gampe9e927f52016-02-29 20:49:38 -0800310void ThreadPool::SetPthreadPriority(int priority) {
311 for (ThreadPoolWorker* worker : threads_) {
312 worker->SetPthreadPriority(priority);
313 }
314}
315
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700316} // namespace art