blob: 5a4dfb8cfd50d1001d9e9b13f8dccae31fa086d3 [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
Vladimir Marko0b6e2832015-09-24 10:41:33 +010019#include "base/bit_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080020#include "base/casts.h"
Vladimir Marko0b6e2832015-09-24 10:41:33 +010021#include "base/logging.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080022#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010023#include "base/time_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080024#include "runtime.h"
Brian Carlstroma3d27182013-11-05 23:22:27 -080025#include "thread-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070027namespace art {
28
Mathieu Chartier720ef762013-08-17 14:46:54 -070029static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070030
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070031ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
32 size_t stack_size)
33 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080034 name_(name) {
Vladimir Marko0b6e2832015-09-24 10:41:33 +010035 // Add an inaccessible page to catch stack overflow.
36 stack_size += kPageSize;
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080037 std::string error_msg;
38 stack_.reset(MemMap::MapAnonymous(name.c_str(), nullptr, stack_size, PROT_READ | PROT_WRITE,
Vladimir Marko5c42c292015-02-25 12:02:49 +000039 false, false, &error_msg));
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080040 CHECK(stack_.get() != nullptr) << error_msg;
Vladimir Marko0b6e2832015-09-24 10:41:33 +010041 CHECK_ALIGNED(stack_->Begin(), kPageSize);
42 int mprotect_result = mprotect(stack_->Begin(), kPageSize, PROT_NONE);
43 CHECK_EQ(mprotect_result, 0) << "Failed to mprotect() bottom page of thread pool worker stack.";
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070044 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070045 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070046 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080047 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_->Begin(), stack_->Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070048 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
49 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
50}
51
52ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070053 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070054}
55
56void ThreadPoolWorker::Run() {
57 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070058 Task* task = nullptr;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080059 thread_pool_->creation_barier_.Wait(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070060 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070061 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070062 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070063 }
64}
65
66void* ThreadPoolWorker::Callback(void* arg) {
67 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
68 Runtime* runtime = Runtime::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070069 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(), true, nullptr, false));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070070 // Do work until its time to shut down.
71 worker->Run();
72 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070073 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070074}
75
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070076void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070077 MutexLock mu(self, task_queue_lock_);
78 tasks_.push_back(task);
79 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070080 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070081 task_queue_condition_.Signal(self);
82 }
83}
84
Nicolas Geoffray629e9352015-11-04 17:22:16 +000085void ThreadPool::RemoveAllTasks(Thread* self) {
86 MutexLock mu(self, task_queue_lock_);
87 tasks_.clear();
88}
89
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080090ThreadPool::ThreadPool(const char* name, size_t num_threads)
91 : name_(name),
92 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070093 task_queue_condition_("task queue condition", task_queue_lock_),
94 completion_condition_("task completion condition", task_queue_lock_),
95 started_(false),
96 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080097 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -070098 start_time_(0),
99 total_wait_time_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800100 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700101 creation_barier_(num_threads + 1),
102 max_active_workers_(num_threads) {
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800103 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700104 while (GetThreadCount() < num_threads) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800105 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
106 GetThreadCount());
Vladimir Marko0b6e2832015-09-24 10:41:33 +0100107 threads_.push_back(
108 new ThreadPoolWorker(this, worker_name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700109 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -0800110 // Wait for all of the threads to attach.
111 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700112}
113
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700114void ThreadPool::SetMaxActiveWorkers(size_t threads) {
115 MutexLock mu(Thread::Current(), task_queue_lock_);
116 CHECK_LE(threads, GetThreadCount());
117 max_active_workers_ = threads;
118}
119
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700120ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700121 {
122 Thread* self = Thread::Current();
123 MutexLock mu(self, task_queue_lock_);
124 // Tell any remaining workers to shut down.
125 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700126 // Broadcast to everyone waiting.
127 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700128 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700129 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700130 // Wait for the threads to finish.
131 STLDeleteElements(&threads_);
132}
133
134void ThreadPool::StartWorkers(Thread* self) {
135 MutexLock mu(self, task_queue_lock_);
136 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700137 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700138 start_time_ = NanoTime();
139 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700140}
141
142void ThreadPool::StopWorkers(Thread* self) {
143 MutexLock mu(self, task_queue_lock_);
144 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700145}
146
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700147Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700148 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700149 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700150 const size_t thread_count = GetThreadCount();
151 // Ensure that we don't use more threads than the maximum active workers.
152 const size_t active_threads = thread_count - waiting_count_;
153 // <= since self is considered an active worker.
154 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700155 Task* task = TryGetTaskLocked();
156 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700157 return task;
158 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700159 }
160
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700161 ++waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700162 if (waiting_count_ == GetThreadCount() && tasks_.empty()) {
163 // We may be done, lets broadcast to the completion condition.
164 completion_condition_.Broadcast(self);
165 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700166 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700167 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700168 if (kMeasureWaitTime) {
169 const uint64_t wait_end = NanoTime();
170 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
171 }
172 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700173 }
174
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700175 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700176 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700177}
178
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700179Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700180 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700181 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700182}
183
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700184Task* ThreadPool::TryGetTaskLocked() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700185 if (started_ && !tasks_.empty()) {
186 Task* task = tasks_.front();
187 tasks_.pop_front();
188 return task;
189 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700190 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700191}
192
Ian Rogers1d54e732013-05-02 21:10:01 -0700193void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
194 if (do_work) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700195 Task* task = nullptr;
196 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700197 task->Run(self);
198 task->Finalize();
199 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700200 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700201 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700202 MutexLock mu(self, task_queue_lock_);
203 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || !tasks_.empty())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700204 if (!may_hold_locks) {
205 completion_condition_.Wait(self);
206 } else {
207 completion_condition_.WaitHoldingLocks(self);
208 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700209 }
210}
211
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700212size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700213 MutexLock mu(self, task_queue_lock_);
214 return tasks_.size();
215}
216
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700217} // namespace art