blob: d8f80fa690a09896da3f35ff91044558deb7ed0d [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
Elliott Hughes1aa246d2012-12-13 09:29:36 -080019#include "base/casts.h"
20#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010021#include "base/time_utils.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080022#include "runtime.h"
Brian Carlstroma3d27182013-11-05 23:22:27 -080023#include "thread-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080024
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070025namespace art {
26
Mathieu Chartier720ef762013-08-17 14:46:54 -070027static constexpr bool kMeasureWaitTime = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070028
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070029ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
30 size_t stack_size)
31 : thread_pool_(thread_pool),
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080032 name_(name) {
33 std::string error_msg;
34 stack_.reset(MemMap::MapAnonymous(name.c_str(), nullptr, stack_size, PROT_READ | PROT_WRITE,
Vladimir Marko5c42c292015-02-25 12:02:49 +000035 false, false, &error_msg));
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080036 CHECK(stack_.get() != nullptr) << error_msg;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070037 const char* reason = "new thread pool worker thread";
Brian Carlstrombcc29262012-11-02 11:36:03 -070038 pthread_attr_t attr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070039 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080040 CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_->Begin(), stack_->Size()), reason);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070041 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
42 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
43}
44
45ThreadPoolWorker::~ThreadPoolWorker() {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070046 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070047}
48
49void ThreadPoolWorker::Run() {
50 Thread* self = Thread::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070051 Task* task = nullptr;
Mathieu Chartier35883cc2012-11-13 14:08:12 -080052 thread_pool_->creation_barier_.Wait(self);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070053 while ((task = thread_pool_->GetTask(self)) != nullptr) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070054 task->Run(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -070055 task->Finalize();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070056 }
57}
58
59void* ThreadPoolWorker::Callback(void* arg) {
60 ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
61 Runtime* runtime = Runtime::Current();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070062 CHECK(runtime->AttachCurrentThread(worker->name_.c_str(), true, nullptr, false));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070063 // Do work until its time to shut down.
64 worker->Run();
65 runtime->DetachCurrentThread();
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070066 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070067}
68
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070069void ThreadPool::AddTask(Thread* self, Task* task) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070070 MutexLock mu(self, task_queue_lock_);
71 tasks_.push_back(task);
72 // If we have any waiters, signal one.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070073 if (started_ && waiting_count_ != 0) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070074 task_queue_condition_.Signal(self);
75 }
76}
77
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -080078ThreadPool::ThreadPool(const char* name, size_t num_threads)
79 : name_(name),
80 task_queue_lock_("task queue lock"),
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070081 task_queue_condition_("task queue condition", task_queue_lock_),
82 completion_condition_("task completion condition", task_queue_lock_),
83 started_(false),
84 shutting_down_(false),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080085 waiting_count_(0),
Ian Rogersd914eb22013-04-18 16:11:15 -070086 start_time_(0),
87 total_wait_time_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080088 // Add one since the caller of constructor waits on the barrier too.
Mathieu Chartier2775ee42013-08-20 17:43:47 -070089 creation_barier_(num_threads + 1),
90 max_active_workers_(num_threads) {
Mathieu Chartier35883cc2012-11-13 14:08:12 -080091 Thread* self = Thread::Current();
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070092 while (GetThreadCount() < num_threads) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -080093 const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
94 GetThreadCount());
95 threads_.push_back(new ThreadPoolWorker(this, worker_name, ThreadPoolWorker::kDefaultStackSize));
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070096 }
Mathieu Chartier35883cc2012-11-13 14:08:12 -080097 // Wait for all of the threads to attach.
98 creation_barier_.Wait(self);
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070099}
100
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700101void ThreadPool::SetMaxActiveWorkers(size_t threads) {
102 MutexLock mu(Thread::Current(), task_queue_lock_);
103 CHECK_LE(threads, GetThreadCount());
104 max_active_workers_ = threads;
105}
106
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700107ThreadPool::~ThreadPool() {
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700108 {
109 Thread* self = Thread::Current();
110 MutexLock mu(self, task_queue_lock_);
111 // Tell any remaining workers to shut down.
112 shutting_down_ = true;
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700113 // Broadcast to everyone waiting.
114 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700115 completion_condition_.Broadcast(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700116 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700117 // Wait for the threads to finish.
118 STLDeleteElements(&threads_);
119}
120
121void ThreadPool::StartWorkers(Thread* self) {
122 MutexLock mu(self, task_queue_lock_);
123 started_ = true;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700124 task_queue_condition_.Broadcast(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700125 start_time_ = NanoTime();
126 total_wait_time_ = 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700127}
128
129void ThreadPool::StopWorkers(Thread* self) {
130 MutexLock mu(self, task_queue_lock_);
131 started_ = false;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700132}
133
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700134Task* ThreadPool::GetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700135 MutexLock mu(self, task_queue_lock_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700136 while (!IsShuttingDown()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700137 const size_t thread_count = GetThreadCount();
138 // Ensure that we don't use more threads than the maximum active workers.
139 const size_t active_threads = thread_count - waiting_count_;
140 // <= since self is considered an active worker.
141 if (active_threads <= max_active_workers_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700142 Task* task = TryGetTaskLocked();
143 if (task != nullptr) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700144 return task;
145 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700146 }
147
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700148 ++waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700149 if (waiting_count_ == GetThreadCount() && tasks_.empty()) {
150 // We may be done, lets broadcast to the completion condition.
151 completion_condition_.Broadcast(self);
152 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700153 const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700154 task_queue_condition_.Wait(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700155 if (kMeasureWaitTime) {
156 const uint64_t wait_end = NanoTime();
157 total_wait_time_ += wait_end - std::max(wait_start, start_time_);
158 }
159 --waiting_count_;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700160 }
161
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700162 // We are shutting down, return null to tell the worker thread to stop looping.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700163 return nullptr;
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700164}
165
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700166Task* ThreadPool::TryGetTask(Thread* self) {
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700167 MutexLock mu(self, task_queue_lock_);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700168 return TryGetTaskLocked();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700169}
170
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700171Task* ThreadPool::TryGetTaskLocked() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700172 if (started_ && !tasks_.empty()) {
173 Task* task = tasks_.front();
174 tasks_.pop_front();
175 return task;
176 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700177 return nullptr;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700178}
179
Ian Rogers1d54e732013-05-02 21:10:01 -0700180void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
181 if (do_work) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700182 Task* task = nullptr;
183 while ((task = TryGetTask(self)) != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700184 task->Run(self);
185 task->Finalize();
186 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700187 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700188 // Wait until each thread is waiting and the task list is empty.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700189 MutexLock mu(self, task_queue_lock_);
190 while (!shutting_down_ && (waiting_count_ != GetThreadCount() || !tasks_.empty())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700191 if (!may_hold_locks) {
192 completion_condition_.Wait(self);
193 } else {
194 completion_condition_.WaitHoldingLocks(self);
195 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700196 }
197}
198
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700199size_t ThreadPool::GetTaskCount(Thread* self) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700200 MutexLock mu(self, task_queue_lock_);
201 return tasks_.size();
202}
203
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700204} // namespace art