• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 HIDDEN {
38 
39 using android::base::StringPrintf;
40 
41 static constexpr bool kMeasureWaitTime = false;
42 
43 #if defined(__BIONIC__)
44 static constexpr bool kUseCustomThreadPoolStack = false;
45 #else
46 static constexpr bool kUseCustomThreadPoolStack = true;
47 #endif
48 
ThreadPoolWorker(AbstractThreadPool * thread_pool,const std::string & name,size_t stack_size)49 ThreadPoolWorker::ThreadPoolWorker(AbstractThreadPool* thread_pool,
50                                    const std::string& name,
51                                    size_t stack_size)
52     : thread_pool_(thread_pool),
53       name_(name) {
54   std::string error_msg;
55   // On Bionic, we know pthreads will give us a big-enough stack with
56   // a guard page, so don't do anything special on Bionic libc.
57   if (kUseCustomThreadPoolStack) {
58     // Add an inaccessible page to catch stack overflow.
59     stack_size += gPageSize;
60     stack_ = MemMap::MapAnonymous(name.c_str(),
61                                   stack_size,
62                                   PROT_READ | PROT_WRITE,
63                                   /*low_4gb=*/ false,
64                                   &error_msg);
65     CHECK(stack_.IsValid()) << error_msg;
66     CHECK_ALIGNED_PARAM(stack_.Begin(), gPageSize);
67     CheckedCall(mprotect,
68                 "mprotect bottom page of thread pool worker stack",
69                 stack_.Begin(),
70                 gPageSize,
71                 PROT_NONE);
72   }
73   const char* reason = "new thread pool worker thread";
74   pthread_attr_t attr;
75   CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason);
76   if (kUseCustomThreadPoolStack) {
77     CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack_.Begin(), stack_.Size()), reason);
78   } else {
79     CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), reason);
80   }
81   CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Callback, this), reason);
82   CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason);
83 }
84 
~ThreadPoolWorker()85 ThreadPoolWorker::~ThreadPoolWorker() {
86   CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "thread pool worker shutdown");
87 }
88 
89 // Set the "nice" priority for tid (0 means self).
SetPriorityForTid(pid_t tid,int priority)90 static void SetPriorityForTid(pid_t tid, int priority) {
91   CHECK_GE(priority, PRIO_MIN);
92   CHECK_LE(priority, PRIO_MAX);
93   int result = setpriority(PRIO_PROCESS, tid, priority);
94   if (result != 0) {
95 #if defined(ART_TARGET_ANDROID)
96     PLOG(WARNING) << "Failed to setpriority to :" << priority;
97 #endif
98     // Setpriority may fail on host due to ulimit issues.
99   }
100 }
101 
SetPthreadPriority(int priority)102 void ThreadPoolWorker::SetPthreadPriority(int priority) {
103 #if defined(ART_TARGET_ANDROID)
104   SetPriorityForTid(pthread_gettid_np(pthread_), priority);
105 #else
106   UNUSED(priority);
107 #endif
108 }
109 
GetPthreadPriority()110 int ThreadPoolWorker::GetPthreadPriority() {
111 #if defined(ART_TARGET_ANDROID)
112   return getpriority(PRIO_PROCESS, pthread_gettid_np(pthread_));
113 #else
114   return 0;
115 #endif
116 }
117 
Run()118 void ThreadPoolWorker::Run() {
119   Thread* self = Thread::Current();
120   Task* task = nullptr;
121   thread_pool_->creation_barier_.Pass(self);
122   while ((task = thread_pool_->GetTask(self)) != nullptr) {
123     task->Run(self);
124     task->Finalize();
125   }
126 }
127 
Callback(void * arg)128 void* ThreadPoolWorker::Callback(void* arg) {
129   ThreadPoolWorker* worker = reinterpret_cast<ThreadPoolWorker*>(arg);
130   Runtime* runtime = Runtime::Current();
131   // Don't run callbacks for ThreadPoolWorkers. These are created for JITThreadPool and
132   // HeapThreadPool and are purely internal threads of the runtime and we don't need to run
133   // callbacks for the thread attach / detach listeners.
134   // (b/251163712) Calling callbacks for heap thread pool workers causes deadlocks in some libjdwp
135   // tests. Deadlocks happen when a GC thread is attached while libjdwp holds the event handler
136   // lock for an event that triggers an entrypoint update from deopt manager.
137   CHECK(runtime->AttachCurrentThread(
138       worker->name_.c_str(),
139       true,
140       // Thread-groups are only tracked by the peer j.l.Thread objects. If we aren't creating peers
141       // we don't need to specify the thread group. We want to place these threads in the System
142       // thread group because that thread group is where important threads that debuggers and
143       // similar tools should not mess with are placed. As this is an internal-thread-pool we might
144       // rely on being able to (for example) wait for all threads to finish some task. If debuggers
145       // are suspending these threads that might not be possible.
146       worker->thread_pool_->create_peers_ ? runtime->GetSystemThreadGroup() : nullptr,
147       worker->thread_pool_->create_peers_,
148       /* should_run_callbacks= */ false));
149   worker->thread_ = Thread::Current();
150   // Mark thread pool workers as runtime-threads.
151   worker->thread_->SetIsRuntimeThread(true);
152   // Do work until its time to shut down.
153   worker->Run();
154   runtime->DetachCurrentThread(/* should_run_callbacks= */ false);
155   // On zygote fork, we wait for this thread to exit completely. Set to highest Java priority
156   // to speed that up.
157   constexpr int kJavaMaxPrioNiceness = -8;
158   SetPriorityForTid(0 /* this thread */, kJavaMaxPrioNiceness);
159   return nullptr;
160 }
161 
AddTask(Thread * self,Task * task)162 void ThreadPool::AddTask(Thread* self, Task* task) {
163   MutexLock mu(self, task_queue_lock_);
164   tasks_.push_back(task);
165   // If we have any waiters, signal one.
166   if (started_ && waiting_count_ != 0) {
167     task_queue_condition_.Signal(self);
168   }
169 }
170 
RemoveAllTasks(Thread * self)171 void ThreadPool::RemoveAllTasks(Thread* self) {
172   // The ThreadPool is responsible for calling Finalize (which usually delete
173   // the task memory) on all the tasks.
174   Task* task = nullptr;
175   do {
176     {
177       MutexLock mu(self, task_queue_lock_);
178       if (tasks_.empty()) {
179         return;
180       }
181       task = tasks_.front();
182       tasks_.pop_front();
183     }
184     task->Finalize();
185   } while (true);
186 }
187 
~ThreadPool()188 ThreadPool::~ThreadPool() {
189   DeleteThreads();
190   RemoveAllTasks(Thread::Current());
191 }
192 
AbstractThreadPool(const char * name,size_t num_threads,bool create_peers,size_t worker_stack_size)193 AbstractThreadPool::AbstractThreadPool(const char* name,
194                                        size_t num_threads,
195                                        bool create_peers,
196                                        size_t worker_stack_size)
197   : name_(name),
198     task_queue_lock_("task queue lock", kGenericBottomLock),
199     task_queue_condition_("task queue condition", task_queue_lock_),
200     completion_condition_("task completion condition", task_queue_lock_),
201     started_(false),
202     shutting_down_(false),
203     waiting_count_(0),
204     start_time_(0),
205     total_wait_time_(0),
206     creation_barier_(0),
207     max_active_workers_(num_threads),
208     create_peers_(create_peers),
209     worker_stack_size_(worker_stack_size) {}
210 
CreateThreads()211 void AbstractThreadPool::CreateThreads() {
212   CHECK(threads_.empty());
213   Thread* self = Thread::Current();
214   {
215     MutexLock mu(self, task_queue_lock_);
216     shutting_down_ = false;
217     // Add one since the caller of constructor waits on the barrier too.
218     creation_barier_.Init(self, max_active_workers_);
219     while (GetThreadCount() < max_active_workers_) {
220       const std::string worker_name = StringPrintf("%s worker thread %zu", name_.c_str(),
221                                                    GetThreadCount());
222       threads_.push_back(
223           new ThreadPoolWorker(this, worker_name, worker_stack_size_));
224     }
225   }
226 }
227 
WaitForWorkersToBeCreated()228 void AbstractThreadPool::WaitForWorkersToBeCreated() {
229   creation_barier_.Increment(Thread::Current(), 0);
230 }
231 
GetWorkers()232 const std::vector<ThreadPoolWorker*>& AbstractThreadPool::GetWorkers() {
233   // Wait for all the workers to be created before returning them.
234   WaitForWorkersToBeCreated();
235   return threads_;
236 }
237 
DeleteThreads()238 void AbstractThreadPool::DeleteThreads() {
239   {
240     Thread* self = Thread::Current();
241     MutexLock mu(self, task_queue_lock_);
242     // Tell any remaining workers to shut down.
243     shutting_down_ = true;
244     // Broadcast to everyone waiting.
245     task_queue_condition_.Broadcast(self);
246     completion_condition_.Broadcast(self);
247   }
248   // Wait for the threads to finish. We expect the user of the pool
249   // not to run multi-threaded calls to `CreateThreads` and `DeleteThreads`,
250   // so we don't guard the field here.
251   STLDeleteElements(&threads_);
252 }
253 
SetMaxActiveWorkers(size_t max_workers)254 void AbstractThreadPool::SetMaxActiveWorkers(size_t max_workers) {
255   MutexLock mu(Thread::Current(), task_queue_lock_);
256   CHECK_LE(max_workers, GetThreadCount());
257   max_active_workers_ = max_workers;
258 }
259 
StartWorkers(Thread * self)260 void AbstractThreadPool::StartWorkers(Thread* self) {
261   MutexLock mu(self, task_queue_lock_);
262   started_ = true;
263   task_queue_condition_.Broadcast(self);
264   start_time_ = NanoTime();
265   total_wait_time_ = 0;
266 }
267 
StopWorkers(Thread * self)268 void AbstractThreadPool::StopWorkers(Thread* self) {
269   MutexLock mu(self, task_queue_lock_);
270   started_ = false;
271 }
272 
HasStarted(Thread * self)273 bool AbstractThreadPool::HasStarted(Thread* self) {
274   MutexLock mu(self, task_queue_lock_);
275   return started_;
276 }
277 
GetTask(Thread * self)278 Task* AbstractThreadPool::GetTask(Thread* self) {
279   MutexLock mu(self, task_queue_lock_);
280   while (!IsShuttingDown()) {
281     const size_t thread_count = GetThreadCount();
282     // Ensure that we don't use more threads than the maximum active workers.
283     const size_t active_threads = thread_count - waiting_count_;
284     // <= since self is considered an active worker.
285     if (active_threads <= max_active_workers_) {
286       Task* task = TryGetTaskLocked();
287       if (task != nullptr) {
288         return task;
289       }
290     }
291 
292     ++waiting_count_;
293     if (waiting_count_ == GetThreadCount() && !HasOutstandingTasks()) {
294       // We may be done, lets broadcast to the completion condition.
295       completion_condition_.Broadcast(self);
296     }
297     const uint64_t wait_start = kMeasureWaitTime ? NanoTime() : 0;
298     task_queue_condition_.Wait(self);
299     if (kMeasureWaitTime) {
300       const uint64_t wait_end = NanoTime();
301       total_wait_time_ += wait_end - std::max(wait_start, start_time_);
302     }
303     --waiting_count_;
304   }
305 
306   // We are shutting down, return null to tell the worker thread to stop looping.
307   return nullptr;
308 }
309 
TryGetTask(Thread * self)310 Task* AbstractThreadPool::TryGetTask(Thread* self) {
311   MutexLock mu(self, task_queue_lock_);
312   return TryGetTaskLocked();
313 }
314 
TryGetTaskLocked()315 Task* ThreadPool::TryGetTaskLocked() {
316   if (HasOutstandingTasks()) {
317     Task* task = tasks_.front();
318     tasks_.pop_front();
319     return task;
320   }
321   return nullptr;
322 }
323 
Wait(Thread * self,bool do_work,bool may_hold_locks)324 void AbstractThreadPool::Wait(Thread* self, bool do_work, bool may_hold_locks) {
325   if (do_work) {
326     CHECK(!create_peers_);
327     Task* task = nullptr;
328     while ((task = TryGetTask(self)) != nullptr) {
329       task->Run(self);
330       task->Finalize();
331     }
332   }
333   // Wait until each thread is waiting and the task list is empty.
334   MutexLock mu(self, task_queue_lock_);
335   while (!shutting_down_ && (waiting_count_ != GetThreadCount() || HasOutstandingTasks())) {
336     if (!may_hold_locks) {
337       completion_condition_.Wait(self);
338     } else {
339       completion_condition_.WaitHoldingLocks(self);
340     }
341   }
342 }
343 
GetTaskCount(Thread * self)344 size_t ThreadPool::GetTaskCount(Thread* self) {
345   MutexLock mu(self, task_queue_lock_);
346   return tasks_.size();
347 }
348 
SetPthreadPriority(int priority)349 void AbstractThreadPool::SetPthreadPriority(int priority) {
350   for (ThreadPoolWorker* worker : threads_) {
351     worker->SetPthreadPriority(priority);
352   }
353 }
354 
CheckPthreadPriority(int priority)355 void AbstractThreadPool::CheckPthreadPriority(int priority) {
356 #if defined(ART_TARGET_ANDROID)
357   for (ThreadPoolWorker* worker : threads_) {
358     CHECK_EQ(worker->GetPthreadPriority(), priority);
359   }
360 #else
361   UNUSED(priority);
362 #endif
363 }
364 
365 }  // namespace art
366