blob: 2a69bc6c10839f097731b68875e29a24297d70a0 [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(),
50 /* addr */ nullptr,
51 stack_size,
52 PROT_READ | PROT_WRITE,
53 /* low_4gb */ false,
54 /* reuse */ false,
55 &error_msg);
56 CHECK(stack_.IsValid()) << error_msg;
57 CHECK_ALIGNED(stack_.Begin(), kPageSize);
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -070058 CheckedCall(mprotect,
59 "mprotect bottom page of thread pool worker stack",
Vladimir Markoc34bebf2018-08-16 16:12:49 +010060 stack_.Begin(),
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -070061 kPageSize,
62 PROT_NONE);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070063 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070064 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070065 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010066 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_.Begin(), stack_.Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070067 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
68 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
69}
70
71ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070072 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070073}
74
Andreas Gampe9e927f52016-02-29 20:49:38 -080075void ThreadPoolWorker::SetPthreadPriority(int priority) {
76 CHECK_GE(priority, PRIO_MIN);
77 CHECK_LE(priority, PRIO_MAX);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010078#if defined(ART_TARGET_ANDROID)
Andreas Gampe9e927f52016-02-29 20:49:38 -080079 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
80 if (result != 0) {
81 PLOG(ERROR) << "Failed to setpriority to :" << priority;
82 }
83#else
84 UNUSED(priority);
85#endif
86}
87
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070088void ThreadPoolWorker::Run() {
89 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070090 Task* task = nullptr;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080091 thread_pool_->creation_barier_.Wait(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070092 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070093 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070094 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070095 }
96}
97
98void* ThreadPoolWorker::Callback(void* arg) {
99 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
100 Runtime* runtime = Runtime::Current();
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800101 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(),
102 true,
103 nullptr,
104 worker->thread_pool_->create_peers_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +0000105 worker->thread_ = Thread::Current();
Calin Juravleccd56952016-12-15 17:57:38 +0000106 // Thread pool workers cannot call into java.
107 worker->thread_->SetCanCallIntoJava(false);
Alex Light53570672018-07-12 11:09:59 -0700108 // Thread pool workers should not be getting paused by user-code.
109 worker->thread_->SetCanBeSuspendedByUserCode(false);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700110 // Do work until its time to shut down.
111 worker->Run();
Alex Light53570672018-07-12 11:09:59 -0700112 // Thread pool worker is finished. We want to allow suspension during shutdown.
113 worker->thread_->SetCanBeSuspendedByUserCode(true);
114 // Thread shuts down.
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700115 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700116 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700117}
118
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700119void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700120 MutexLock mu(self, task_queue_lock_);
121 tasks_.push_back(task);
122 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700123 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700124 task_queue_condition_.Signal(self);
125 }
126}
127
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000128void ThreadPool::RemoveAllTasks(Thread* self) {
129 MutexLock mu(self, task_queue_lock_);
130 tasks_.clear();
131}
132
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800133ThreadPool::ThreadPool(const char* name, size_t num_threads, bool create_peers)
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800134 : name_(name),
135 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700136 task_queue_condition_("task queue condition", task_queue_lock_),
137 completion_condition_("task completion condition", task_queue_lock_),
138 started_(false),
139 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800140 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -0700141 start_time_(0),
142 total_wait_time_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800143 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700144 creation_barier_(num_threads + 1),
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800145 max_active_workers_(num_threads),
146 create_peers_(create_peers) {
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800147 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700148 while (GetThreadCount() < num_threads) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800149 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
150 GetThreadCount());
Vladimir Marko0b6e2832015-09-24 10:41:33 +0100151 threads_.push_back(
152 new ThreadPoolWorker(this, worker_name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700153 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800154 // Wait for all of the threads to attach.
155 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700156}
157
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700158void ThreadPool::SetMaxActiveWorkers(size_t threads) {
159 MutexLock mu(Thread::Current(), task_queue_lock_);
160 CHECK_LE(threads, GetThreadCount());
161 max_active_workers_ = threads;
162}
163
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700164ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700165 {
166 Thread* self = Thread::Current();
167 MutexLock mu(self, task_queue_lock_);
168 // Tell any remaining workers to shut down.
169 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700170 // Broadcast to everyone waiting.
171 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700172 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700173 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700174 // Wait for the threads to finish.
175 STLDeleteElements(&threads_);
176}
177
178void ThreadPool::StartWorkers(Thread* self) {
179 MutexLock mu(self, task_queue_lock_);
180 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700181 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700182 start_time_ = NanoTime();
183 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700184}
185
186void ThreadPool::StopWorkers(Thread* self) {
187 MutexLock mu(self, task_queue_lock_);
188 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700189}
190
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700191Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700192 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700193 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700194 const size_t thread_count = GetThreadCount();
195 // Ensure that we don't use more threads than the maximum active workers.
196 const size_t active_threads = thread_count - waiting_count_;
197 // <= since self is considered an active worker.
198 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700199 Task* task = TryGetTaskLocked();
200 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700201 return task;
202 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700203 }
204
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700205 ++waiting_count_;
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800206 if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700207 // We may be done, lets broadcast to the completion condition.
208 completion_condition_.Broadcast(self);
209 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700210 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700211 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700212 if (kMeasureWaitTime) {
213 const uint64_t wait_end = NanoTime();
214 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
215 }
216 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700217 }
218
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700219 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700220 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700221}
222
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700223Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700224 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700225 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700226}
227
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700228Task* ThreadPool::TryGetTaskLocked() {
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800229 if (HasOutstandingTasks()) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700230 Task* task = tasks_.front();
231 tasks_.pop_front();
232 return task;
233 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700234 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700235}
236
Ian Rogers1d54e732013-05-02 21:10:01 -0700237void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
238 if (do_work) {
Andreas Gampeb15de0c2017-01-24 13:12:19 -0800239 CHECK(!create_peers_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700240 Task* task = nullptr;
241 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700242 task->Run(self);
243 task->Finalize();
244 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700245 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700246 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700247 MutexLock mu(self, task_queue_lock_);
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800248 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700249 if (!may_hold_locks) {
250 completion_condition_.Wait(self);
251 } else {
252 completion_condition_.WaitHoldingLocks(self);
253 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700254 }
255}
256
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700257size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700258 MutexLock mu(self, task_queue_lock_);
259 return tasks_.size();
260}
261
Andreas Gampe9e927f52016-02-29 20:49:38 -0800262void ThreadPool::SetPthreadPriority(int priority) {
263 for (ThreadPoolWorker* worker : threads_) {
264 worker->SetPthreadPriority(priority);
265 }
266}
267
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700268} // namespace art