1 
2 /*
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 
18 #include "thread_pool.h"
19 
20 #include <sys/mman.h>
21 #include <sys/resource.h>
22 #include <sys/time.h>
23 
24 #include <pthread.h>
25 
26 #include <android-base/logging.h>
27 #include <android-base/stringprintf.h>
28 
29 #include "base/bit_utils.h"
30 #include "base/casts.h"
31 #include "base/stl_util.h"
32 #include "base/time_utils.h"
33 #include "base/utils.h"
34 #include "runtime.h"
35 #include "thread-current-inl.h"
36 
37 namespace art {
38 
39 using android::base::StringPrintf;
40 
41 static constexpr bool kMeasureWaitTime = false;
42 
ThreadPoolWorker(ThreadPool * thread_pool,const std::string & name,size_t stack_size)43 ThreadPoolWorker::ThreadPoolWorker(ThreadPool* thread_pool, const std::string& name,
44                                    size_t stack_size)
45     : thread_pool_(thread_pool),
46       name_(name) {
47   // Add an inaccessible page to catch stack overflow.
48   stack_size += kPageSize;
49   std::string error_msg;
50   stack_ = MemMap::MapAnonymous(name.c_str(),
51                                 stack_size,
52                                 PROT_READ | PROT_WRITE,
53                                 /*low_4gb=*/ false,
54                                 &error_msg);
55   CHECK(stack_.IsValid()) << error_msg;
56   CHECK_ALIGNED(stack_.Begin(), kPageSize);
57   CheckedCall(mprotect,
58               "mprotect bottom page of thread pool worker stack",
59               stack_.Begin(),
60               kPageSize,
61               PROT_NONE);
62   const char* reason = "new thread pool worker thread";
63   pthread_attr_t attr;
64   CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
65   CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_.Begin(), stack_.Size()), reason);
66   CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
67   CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
68 }
69 
~ThreadPoolWorker()70 ThreadPoolWorker::~ThreadPoolWorker() {
71   CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
72 }
73 
SetPthreadPriority(int priority)74 void ThreadPoolWorker::SetPthreadPriority(int priority) {
75   CHECK_GE(priority, PRIO_MIN);
76   CHECK_LE(priority, PRIO_MAX);
77 #if defined(ART_TARGET_ANDROID)
78   int result = setpriority(PRIO_PROCESS, pthread_gettid_np(pthread_), priority);
79   if (result != 0) {
80     PLOG(ERROR) << "Failed to setpriority to :" << priority;
81   }
82 #else
83   UNUSED(priority);
84 #endif
85 }
86 
Run()87 void ThreadPoolWorker::Run() {
88   Thread* self = Thread::Current();
89   Task* task = nullptr;
90   thread_pool_->creation_barier_.Pass(self);
91   while ((task = thread_pool_->GetTask(self)) != nullptr) {
92     task->Run(self);
93     task->Finalize();
94   }
95 }
96 
Callback(void * arg)97 void* ThreadPoolWorker::Callback(void* arg) {
98   ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
99   Runtime* runtime = Runtime::Current();
100   CHECK(runtime->AttachCurrentThread(
101       worker->name_.c_str(),
102       true,
103       // Thread-groups are only tracked by the peer j.l.Thread objects. If we aren't creating peers
104       // we don't need to specify the thread group. We want to place these threads in the System
105       // thread group because that thread group is where important threads that debuggers and
106       // similar tools should not mess with are placed. As this is an internal-thread-pool we might
107       // rely on being able to (for example) wait for all threads to finish some task. If debuggers
108       // are suspending these threads that might not be possible.
109       worker->thread_pool_->create_peers_ ? runtime->GetSystemThreadGroup() : nullptr,
110       worker->thread_pool_->create_peers_));
111   worker->thread_ = Thread::Current();
112   // Mark thread pool workers as runtime-threads.
113   worker->thread_->SetIsRuntimeThread(true);
114   // Do work until its time to shut down.
115   worker->Run();
116   runtime->DetachCurrentThread();
117   return nullptr;
118 }
119 
AddTask(Thread * self,Task * task)120 void ThreadPool::AddTask(Thread* self, Task* task) {
121   MutexLock mu(self, task_queue_lock_);
122   tasks_.push_back(task);
123   // If we have any waiters, signal one.
124   if (started_ && waiting_count_ != 0) {
125     task_queue_condition_.Signal(self);
126   }
127 }
128 
RemoveAllTasks(Thread * self)129 void ThreadPool::RemoveAllTasks(Thread* self) {
130   // The ThreadPool is responsible for calling Finalize (which usually delete
131   // the task memory) on all the tasks.
132   Task* task = nullptr;
133   while ((task = TryGetTask(self)) != nullptr) {
134     task->Finalize();
135   }
136   MutexLock mu(self, task_queue_lock_);
137   tasks_.clear();
138 }
139 
ThreadPool(const char * name,size_t num_threads,bool create_peers,size_t worker_stack_size)140 ThreadPool::ThreadPool(const char* name,
141                        size_t num_threads,
142                        bool create_peers,
143                        size_t worker_stack_size)
144   : name_(name),
145     task_queue_lock_("task queue lock"),
146     task_queue_condition_("task queue condition", task_queue_lock_),
147     completion_condition_("task completion condition", task_queue_lock_),
148     started_(false),
149     shutting_down_(false),
150     waiting_count_(0),
151     start_time_(0),
152     total_wait_time_(0),
153     creation_barier_(0),
154     max_active_workers_(num_threads),
155     create_peers_(create_peers),
156     worker_stack_size_(worker_stack_size) {
157   CreateThreads();
158 }
159 
CreateThreads()160 void ThreadPool::CreateThreads() {
161   CHECK(threads_.empty());
162   Thread* self = Thread::Current();
163   {
164     MutexLock mu(self, task_queue_lock_);
165     shutting_down_ = false;
166     // Add one since the caller of constructor waits on the barrier too.
167     creation_barier_.Init(self, max_active_workers_);
168     while (GetThreadCount() < max_active_workers_) {
169       const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
170                                                    GetThreadCount());
171       threads_.push_back(
172           new ThreadPoolWorker(this, worker_name, worker_stack_size_));
173     }
174   }
175 }
176 
WaitForWorkersToBeCreated()177 void ThreadPool::WaitForWorkersToBeCreated() {
178   creation_barier_.Increment(Thread::Current(), 0);
179 }
180 
GetWorkers()181 const std::vector<ThreadPoolWorker*>& ThreadPool::GetWorkers() {
182   // Wait for all the workers to be created before returning them.
183   WaitForWorkersToBeCreated();
184   return threads_;
185 }
186 
DeleteThreads()187 void ThreadPool::DeleteThreads() {
188   {
189     Thread* self = Thread::Current();
190     MutexLock mu(self, task_queue_lock_);
191     // Tell any remaining workers to shut down.
192     shutting_down_ = true;
193     // Broadcast to everyone waiting.
194     task_queue_condition_.Broadcast(self);
195     completion_condition_.Broadcast(self);
196   }
197   // Wait for the threads to finish. We expect the user of the pool
198   // not to run multi-threaded calls to `CreateThreads` and `DeleteThreads`,
199   // so we don't guard the field here.
200   STLDeleteElements(&threads_);
201 }
202 
SetMaxActiveWorkers(size_t max_workers)203 void ThreadPool::SetMaxActiveWorkers(size_t max_workers) {
204   MutexLock mu(Thread::Current(), task_queue_lock_);
205   CHECK_LE(max_workers, GetThreadCount());
206   max_active_workers_ = max_workers;
207 }
208 
~ThreadPool()209 ThreadPool::~ThreadPool() {
210   DeleteThreads();
211   RemoveAllTasks(Thread::Current());
212 }
213 
StartWorkers(Thread * self)214 void ThreadPool::StartWorkers(Thread* self) {
215   MutexLock mu(self, task_queue_lock_);
216   started_ = true;
217   task_queue_condition_.Broadcast(self);
218   start_time_ = NanoTime();
219   total_wait_time_ = 0;
220 }
221 
StopWorkers(Thread * self)222 void ThreadPool::StopWorkers(Thread* self) {
223   MutexLock mu(self, task_queue_lock_);
224   started_ = false;
225 }
226 
GetTask(Thread * self)227 Task* ThreadPool::GetTask(Thread* self) {
228   MutexLock mu(self, task_queue_lock_);
229   while (!IsShuttingDown()) {
230     const size_t thread_count = GetThreadCount();
231     // Ensure that we don't use more threads than the maximum active workers.
232     const size_t active_threads = thread_count - waiting_count_;
233     // <= since self is considered an active worker.
234     if (active_threads <= max_active_workers_) {
235       Task* task = TryGetTaskLocked();
236       if (task != nullptr) {
237         return task;
238       }
239     }
240 
241     ++waiting_count_;
242     if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
243       // We may be done, lets broadcast to the completion condition.
244       completion_condition_.Broadcast(self);
245     }
246     const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
247     task_queue_condition_.Wait(self);
248     if (kMeasureWaitTime) {
249       const uint64_t wait_end = NanoTime();
250       total_wait_time_ += wait_end - std::max(wait_start, start_time_);
251     }
252     --waiting_count_;
253   }
254 
255   // We are shutting down, return null to tell the worker thread to stop looping.
256   return nullptr;
257 }
258 
TryGetTask(Thread * self)259 Task* ThreadPool::TryGetTask(Thread* self) {
260   MutexLock mu(self, task_queue_lock_);
261   return TryGetTaskLocked();
262 }
263 
TryGetTaskLocked()264 Task* ThreadPool::TryGetTaskLocked() {
265   if (HasOutstandingTasks()) {
266     Task* task = tasks_.front();
267     tasks_.pop_front();
268     return task;
269   }
270   return nullptr;
271 }
272 
Wait(Thread * self,bool do_work,bool may_hold_locks)273 void ThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
274   if (do_work) {
275     CHECK(!create_peers_);
276     Task* task = nullptr;
277     while ((task = TryGetTask(self)) != nullptr) {
278       task->Run(self);
279       task->Finalize();
280     }
281   }
282   // Wait until each thread is waiting and the task list is empty.
283   MutexLock mu(self, task_queue_lock_);
284   while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
285     if (!may_hold_locks) {
286       completion_condition_.Wait(self);
287     } else {
288       completion_condition_.WaitHoldingLocks(self);
289     }
290   }
291 }
292 
GetTaskCount(Thread * self)293 size_t ThreadPool::GetTaskCount(Thread* self) {
294   MutexLock mu(self, task_queue_lock_);
295   return tasks_.size();
296 }
297 
SetPthreadPriority(int priority)298 void ThreadPool::SetPthreadPriority(int priority) {
299   for (ThreadPoolWorker* worker : threads_) {
300     worker->SetPthreadPriority(priority);
301   }
302 }
303 
304 }  // namespace art
305