blob: 6abdca176d3c87b491dd658ddb4343e4c09f79aa [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080024#include "android-base/stringprintf.h"
25
Vladimir Marko0b6e2832015-09-24 10:41:33 +010026#include "base/bit_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/casts.h"
Vladimir Marko0b6e2832015-09-24 10:41:33 +010028#include "base/logging.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010030#include "base/time_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "runtime.h"
Brian Carlstroma3d27182013-11-05 23:22:27 -080032#include "thread-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080033
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070034namespace art {
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036using android::base::StringPrintf;
37
Mathieu Chartier720ef762013-08-17 14:46:54 -070038static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070039
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070040ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
41 size_t stack_size)
42 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080043 name_(name) {
Vladimir Marko0b6e2832015-09-24 10:41:33 +010044 // Add an inaccessible page to catch stack overflow.
45 stack_size += kPageSize;
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080046 std::string error_msg;
47 stack_.reset(MemMap::MapAnonymous(name.c_str(), nullptr, stack_size, PROT_READ | PROT_WRITE,
Vladimir Marko5c42c292015-02-25 12:02:49 +000048 false, false, &error_msg));
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080049 CHECK(stack_.get() != nullptr) << error_msg;
Vladimir Marko0b6e2832015-09-24 10:41:33 +010050 CHECK_ALIGNED(stack_->Begin(), kPageSize);
51 int mprotect_result = mprotect(stack_->Begin(), kPageSize, PROT_NONE);
52 CHECK_EQ(mprotect_result, 0) << "Failed to mprotect() bottom page of thread pool worker stack.";
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070053 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070054 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070055 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080056 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_->Begin(), stack_->Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070057 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
58 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
59}
60
61ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070062 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070063}
64
Andreas Gampe9e927f52016-02-29 20:49:38 -080065void ThreadPoolWorker::SetPthreadPriority(int priority) {
66 CHECK_GE(priority, PRIO_MIN);
67 CHECK_LE(priority, PRIO_MAX);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010068#if defined(ART_TARGET_ANDROID)
Andreas Gampe9e927f52016-02-29 20:49:38 -080069 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
70 if (result != 0) {
71 PLOG(ERROR) << "Failed to setpriority to :" << priority;
72 }
73#else
74 UNUSED(priority);
75#endif
76}
77
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070078void ThreadPoolWorker::Run() {
79 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070080 Task* task = nullptr;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080081 thread_pool_->creation_barier_.Wait(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070082 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070083 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070084 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070085 }
86}
87
88void* ThreadPoolWorker::Callback(void* arg) {
89 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
90 Runtime* runtime = Runtime::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070091 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(), true, nullptr, false));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +000092 worker->thread_ = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070093 // Do work until its time to shut down.
94 worker->Run();
95 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070096 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070097}
98
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070099void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700100 MutexLock mu(self, task_queue_lock_);
101 tasks_.push_back(task);
102 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700103 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700104 task_queue_condition_.Signal(self);
105 }
106}
107
Nicolas Geoffray629e9352015-11-04 17:22:16 +0000108void ThreadPool::RemoveAllTasks(Thread* self) {
109 MutexLock mu(self, task_queue_lock_);
110 tasks_.clear();
111}
112
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800113ThreadPool::ThreadPool(const char* name, size_t num_threads)
114 : name_(name),
115 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700116 task_queue_condition_("task queue condition", task_queue_lock_),
117 completion_condition_("task completion condition", task_queue_lock_),
118 started_(false),
119 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800120 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -0700121 start_time_(0),
122 total_wait_time_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800123 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700124 creation_barier_(num_threads + 1),
125 max_active_workers_(num_threads) {
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800126 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700127 while (GetThreadCount() < num_threads) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800128 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
129 GetThreadCount());
Vladimir Marko0b6e2832015-09-24 10:41:33 +0100130 threads_.push_back(
131 new ThreadPoolWorker(this, worker_name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700132 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800133 // Wait for all of the threads to attach.
134 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700135}
136
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700137void ThreadPool::SetMaxActiveWorkers(size_t threads) {
138 MutexLock mu(Thread::Current(), task_queue_lock_);
139 CHECK_LE(threads, GetThreadCount());
140 max_active_workers_ = threads;
141}
142
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700143ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700144 {
145 Thread* self = Thread::Current();
146 MutexLock mu(self, task_queue_lock_);
147 // Tell any remaining workers to shut down.
148 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700149 // Broadcast to everyone waiting.
150 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700151 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700152 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700153 // Wait for the threads to finish.
154 STLDeleteElements(&threads_);
155}
156
157void ThreadPool::StartWorkers(Thread* self) {
158 MutexLock mu(self, task_queue_lock_);
159 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700160 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700161 start_time_ = NanoTime();
162 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700163}
164
165void ThreadPool::StopWorkers(Thread* self) {
166 MutexLock mu(self, task_queue_lock_);
167 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700168}
169
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700170Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700171 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700172 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700173 const size_t thread_count = GetThreadCount();
174 // Ensure that we don't use more threads than the maximum active workers.
175 const size_t active_threads = thread_count - waiting_count_;
176 // <= since self is considered an active worker.
177 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700178 Task* task = TryGetTaskLocked();
179 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700180 return task;
181 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700182 }
183
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700184 ++waiting_count_;
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800185 if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700186 // We may be done, lets broadcast to the completion condition.
187 completion_condition_.Broadcast(self);
188 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700189 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700190 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700191 if (kMeasureWaitTime) {
192 const uint64_t wait_end = NanoTime();
193 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
194 }
195 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700196 }
197
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700198 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700199 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700200}
201
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700202Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700203 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700204 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700205}
206
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700207Task* ThreadPool::TryGetTaskLocked() {
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800208 if (HasOutstandingTasks()) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700209 Task* task = tasks_.front();
210 tasks_.pop_front();
211 return task;
212 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700213 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700214}
215
Ian Rogers1d54e732013-05-02 21:10:01 -0700216void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
217 if (do_work) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700218 Task* task = nullptr;
219 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700220 task->Run(self);
221 task->Finalize();
222 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700223 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700224 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700225 MutexLock mu(self, task_queue_lock_);
Andreas Gampe6f3a70f2016-11-16 13:58:05 -0800226 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700227 if (!may_hold_locks) {
228 completion_condition_.Wait(self);
229 } else {
230 completion_condition_.WaitHoldingLocks(self);
231 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700232 }
233}
234
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700235size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700236 MutexLock mu(self, task_queue_lock_);
237 return tasks_.size();
238}
239
Andreas Gampe9e927f52016-02-29 20:49:38 -0800240void ThreadPool::SetPthreadPriority(int priority) {
241 for (ThreadPoolWorker* worker : threads_) {
242 worker->SetPthreadPriority(priority);
243 }
244}
245
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700246} // namespace art