blob: 3bf577961a8b9efd58987a222e022ff64cd21691 [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 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
The Android Open Source Project7a4c8392009-03-05 14:34:35 -080017// #define LOG_NDEBUG 0
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080018#define LOG_TAG "libutils.threads"
19
Mark Salyzyn5bed8032014-04-30 11:10:46 -070020#include <assert.h>
Mathias Agopian22dbf392017-02-28 15:06:51 -080021#include <utils/AndroidThreads.h>
Rick Yiuf7f44422019-12-26 19:35:03 +080022#include <utils/Thread.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080023
Yabin Cui4a6e5a32015-01-26 19:48:54 -080024#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025# include <sys/resource.h>
Yabin Cui4a6e5a32015-01-26 19:48:54 -080026#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080027# include <windows.h>
28# include <stdint.h>
29# include <process.h>
30# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
31#endif
32
Elliott Hughes292ccd32014-12-15 12:52:53 -080033#if defined(__linux__)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080034#include <sys/prctl.h>
35#endif
36
Mark Salyzyn5bed8032014-04-30 11:10:46 -070037#include <utils/Log.h>
38
Rick Yiuf7f44422019-12-26 19:35:03 +080039#if defined(__ANDROID__)
40#include <processgroup/processgroup.h>
Suren Baghdasaryan02843332018-12-21 12:30:16 -080041#include <processgroup/sched_policy.h>
Rick Yiuf7f44422019-12-26 19:35:03 +080042#endif
Mark Salyzyn5bed8032014-04-30 11:10:46 -070043
Elliott Hughes9b828ad2015-07-30 08:47:35 -070044#if defined(__ANDROID__)
Mark Salyzyn5bed8032014-04-30 11:10:46 -070045# define __android_unused
46#else
47# define __android_unused __attribute__((__unused__))
48#endif
49
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080050/*
51 * ===========================================================================
52 * Thread wrappers
53 * ===========================================================================
54 */
55
56using namespace android;
57
58// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -080059#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080060// ----------------------------------------------------------------------------
61
62/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070063 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080064 *
65 * We create it "detached", so it cleans up after itself.
66 */
67
68typedef void* (*android_pthread_entry)(void*);
69
Rick Yiuf7f44422019-12-26 19:35:03 +080070#if defined(__ANDROID__)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080071struct thread_data_t {
72 thread_func_t entryFunction;
73 void* userData;
74 int priority;
75 char * threadName;
76
77 // we use this trampoline when we need to set the priority with
Glenn Kastend731f072011-07-11 15:59:22 -070078 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080079 static int trampoline(const thread_data_t* t) {
80 thread_func_t f = t->entryFunction;
81 void* u = t->userData;
82 int prio = t->priority;
83 char * name = t->threadName;
84 delete t;
85 setpriority(PRIO_PROCESS, 0, prio);
Rick Yiuf7f44422019-12-26 19:35:03 +080086
87 // A new thread will be in its parent's sched group by default,
88 // so we just need to handle the background case.
Wei Wangc39d60d2021-09-29 15:35:58 -070089 // currently set to system_background group which is different
90 // from background group for app.
Glenn Kastenfe34e452012-04-30 16:03:30 -070091 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
Wei Wangc39d60d2021-09-29 15:35:58 -070092 SetTaskProfiles(0, {"SCHED_SP_SYSTEM"}, true);
Dianne Hackborna78bab02010-09-09 15:50:18 -070093 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -080094
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080095 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080096 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080097 free(name);
98 }
99 return f(u);
100 }
101};
Rick Yiuf7f44422019-12-26 19:35:03 +0800102#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800103
Mathias Agopian6090df82013-03-07 15:34:28 -0800104void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -0800105#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -0800106 // Mac OS doesn't have this, and we build libutil for the host too
107 int hasAt = 0;
108 int hasDot = 0;
109 const char *s = name;
110 while (*s) {
111 if (*s == '.') hasDot = 1;
112 else if (*s == '@') hasAt = 1;
113 s++;
114 }
115 int len = s - name;
116 if (len < 15 || hasAt || !hasDot) {
117 s = name;
118 } else {
119 s = name + len - 15;
120 }
121 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
122#endif
123}
124
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800125int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
126 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700127 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800128 int32_t threadPriority,
129 size_t threadStackSize,
130 android_thread_id_t *threadId)
131{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800132 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800133 pthread_attr_init(&attr);
134 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
135
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700136#if defined(__ANDROID__) /* valgrind is rejecting RT-priority create reqs */
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800137 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700138 // Now that the pthread_t has a method to find the associated
139 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
140 // this trampoline in some cases as the parent could set the properties
141 // for the child. However, there would be a race condition because the
142 // child becomes ready immediately, and it doesn't work for the name.
143 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
144 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800145 thread_data_t* t = new thread_data_t;
146 t->priority = threadPriority;
147 t->threadName = threadName ? strdup(threadName) : NULL;
148 t->entryFunction = entryFunction;
149 t->userData = userData;
150 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800151 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800152 }
153#endif
154
155 if (threadStackSize) {
156 pthread_attr_setstacksize(&attr, threadStackSize);
157 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800158
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800159 errno = 0;
160 pthread_t thread;
161 int result = pthread_create(&thread, &attr,
162 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700163 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800164 if (result != 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700165 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800166 "(android threadPriority=%d)",
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700167 entryFunction, result, strerror(errno), threadPriority);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800168 return 0;
169 }
170
Glenn Kastena538e262011-06-02 08:59:28 -0700171 // Note that *threadID is directly available to the parent only, as it is
172 // assigned after the child starts. Use memory barrier / lock if the child
173 // or other threads also need access.
Yi Konge1731a42018-07-16 18:11:34 -0700174 if (threadId != nullptr) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800175 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
176 }
177 return 1;
178}
179
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700180#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700181static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
182{
183 return (pthread_t) thread;
184}
185#endif
186
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800187android_thread_id_t androidGetThreadId()
188{
189 return (android_thread_id_t)pthread_self();
190}
191
192// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800193#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800194// ----------------------------------------------------------------------------
195
196/*
197 * Trampoline to make us __stdcall-compliant.
198 *
199 * We're expected to delete "vDetails" when we're done.
200 */
201struct threadDetails {
202 int (*func)(void*);
203 void* arg;
204};
205static __stdcall unsigned int threadIntermediary(void* vDetails)
206{
207 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
208 int result;
209
210 result = (*(pDetails->func))(pDetails->arg);
211
212 delete pDetails;
213
Steve Block8b4cf772011-10-12 17:27:03 +0100214 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800215 return (unsigned int) result;
216}
217
218/*
219 * Create and run a new thread.
220 */
221static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
222{
223 HANDLE hThread;
224 struct threadDetails* pDetails = new threadDetails; // must be on heap
225 unsigned int thrdaddr;
226
227 pDetails->func = fn;
228 pDetails->arg = arg;
229
230#if defined(HAVE__BEGINTHREADEX)
231 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
232 &thrdaddr);
233 if (hThread == 0)
234#elif defined(HAVE_CREATETHREAD)
235 hThread = CreateThread(NULL, 0,
236 (LPTHREAD_START_ROUTINE) threadIntermediary,
237 (void*) pDetails, 0, (DWORD*) &thrdaddr);
238 if (hThread == NULL)
239#endif
240 {
Steve Block8b4cf772011-10-12 17:27:03 +0100241 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800242 return false;
243 }
244
245#if defined(HAVE_CREATETHREAD)
246 /* close the management handle */
247 CloseHandle(hThread);
248#endif
249
250 if (id != NULL) {
251 *id = (android_thread_id_t)thrdaddr;
252 }
253
254 return true;
255}
256
257int androidCreateRawThreadEtc(android_thread_func_t fn,
258 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700259 const char* /*threadName*/,
260 int32_t /*threadPriority*/,
261 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800262 android_thread_id_t *threadId)
263{
264 return doCreateThread( fn, userData, threadId);
265}
266
267android_thread_id_t androidGetThreadId()
268{
269 return (android_thread_id_t)GetCurrentThreadId();
270}
271
272// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800273#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800274
275// ----------------------------------------------------------------------------
276
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800277int androidCreateThread(android_thread_func_t fn, void* arg)
278{
279 return createThreadEtc(fn, arg);
280}
281
282int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
283{
284 return createThreadEtc(fn, arg, "android:unnamed_thread",
285 PRIORITY_DEFAULT, 0, id);
286}
287
288static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
289
290int androidCreateThreadEtc(android_thread_func_t entryFunction,
291 void *userData,
292 const char* threadName,
293 int32_t threadPriority,
294 size_t threadStackSize,
295 android_thread_id_t *threadId)
296{
297 return gCreateThreadFn(entryFunction, userData, threadName,
298 threadPriority, threadStackSize, threadId);
299}
300
301void androidSetCreateThreadFunc(android_create_thread_fn func)
302{
303 gCreateThreadFn = func;
304}
305
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700306#if defined(__ANDROID__)
Rick Yiufa02bb92020-09-27 11:21:11 +0800307int androidSetThreadPriority(pid_t tid, int pri)
308{
Dianne Hackborn235af972009-12-07 17:59:37 -0800309 int rc = 0;
310 int lasterr = 0;
Rick Yiuf7f44422019-12-26 19:35:03 +0800311 int curr_pri = getpriority(PRIO_PROCESS, tid);
312
313 if (curr_pri == pri) {
314 return rc;
315 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800316
Rick Yiufa02bb92020-09-27 11:21:11 +0800317 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Wei Wangc39d60d2021-09-29 15:35:58 -0700318 rc = SetTaskProfiles(tid, {"SCHED_SP_SYSTEM"}, true) ? 0 : -1;
Rick Yiufa02bb92020-09-27 11:21:11 +0800319 } else if (curr_pri >= ANDROID_PRIORITY_BACKGROUND) {
Wei Wange73180f2021-12-09 18:51:28 -0800320 rc = SetTaskProfiles(tid, {"SCHED_SP_FOREGROUND"}, true) ? 0 : -1;
Rick Yiufa02bb92020-09-27 11:21:11 +0800321 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800322
Rick Yiufa02bb92020-09-27 11:21:11 +0800323 if (rc) {
324 lasterr = errno;
Dianne Hackborn235af972009-12-07 17:59:37 -0800325 }
326
327 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
328 rc = INVALID_OPERATION;
329 } else {
330 errno = lasterr;
331 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800332
Dianne Hackborn235af972009-12-07 17:59:37 -0800333 return rc;
334}
335
Andreas Huber8ddbed92011-09-15 12:21:40 -0700336int androidGetThreadPriority(pid_t tid) {
337 return getpriority(PRIO_PROCESS, tid);
338}
339
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700340#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700341
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800342namespace android {
343
344/*
345 * ===========================================================================
346 * Mutex class
347 * ===========================================================================
348 */
349
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800350#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700351// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800352#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800353
354Mutex::Mutex()
355{
356 HANDLE hMutex;
357
358 assert(sizeof(hMutex) == sizeof(mState));
359
360 hMutex = CreateMutex(NULL, FALSE, NULL);
361 mState = (void*) hMutex;
362}
363
Dan Willemsen528f1442017-11-29 18:06:11 -0800364Mutex::Mutex(const char* /*name*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800365{
366 // XXX: name not used for now
367 HANDLE hMutex;
368
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200369 assert(sizeof(hMutex) == sizeof(mState));
370
371 hMutex = CreateMutex(NULL, FALSE, NULL);
372 mState = (void*) hMutex;
373}
374
Dan Willemsen528f1442017-11-29 18:06:11 -0800375Mutex::Mutex(int /*type*/, const char* /*name*/)
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200376{
377 // XXX: type and name not used for now
378 HANDLE hMutex;
379
380 assert(sizeof(hMutex) == sizeof(mState));
381
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800382 hMutex = CreateMutex(NULL, FALSE, NULL);
383 mState = (void*) hMutex;
384}
385
386Mutex::~Mutex()
387{
388 CloseHandle((HANDLE) mState);
389}
390
391status_t Mutex::lock()
392{
393 DWORD dwWaitResult;
394 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
Elliott Hughes643268f2018-10-08 11:10:11 -0700395 return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800396}
397
398void Mutex::unlock()
399{
400 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100401 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800402}
403
404status_t Mutex::tryLock()
405{
406 DWORD dwWaitResult;
407
408 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
409 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100410 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800411 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
412}
413
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800414#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800415
416
417/*
418 * ===========================================================================
419 * Condition class
420 * ===========================================================================
421 */
422
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800423#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700424// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800425#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800426
427/*
428 * Windows doesn't have a condition variable solution. It's possible
429 * to create one, but it's easy to get it wrong. For a discussion, and
430 * the origin of this implementation, see:
431 *
432 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
433 *
434 * The implementation shown on the page does NOT follow POSIX semantics.
435 * As an optimization they require acquiring the external mutex before
436 * calling signal() and broadcast(), whereas POSIX only requires grabbing
437 * it before calling wait(). The implementation here has been un-optimized
438 * to have the correct behavior.
439 */
440typedef struct WinCondition {
441 // Number of waiting threads.
442 int waitersCount;
443
444 // Serialize access to waitersCount.
445 CRITICAL_SECTION waitersCountLock;
446
447 // Semaphore used to queue up threads waiting for the condition to
448 // become signaled.
449 HANDLE sema;
450
451 // An auto-reset event used by the broadcast/signal thread to wait
452 // for all the waiting thread(s) to wake up and be released from
453 // the semaphore.
454 HANDLE waitersDone;
455
456 // This mutex wouldn't be necessary if we required that the caller
457 // lock the external mutex before calling signal() and broadcast().
458 // I'm trying to mimic pthread semantics though.
459 HANDLE internalMutex;
460
461 // Keeps track of whether we were broadcasting or signaling. This
462 // allows us to optimize the code if we're just signaling.
463 bool wasBroadcast;
464
465 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
466 {
467 // Increment the wait count, avoiding race conditions.
468 EnterCriticalSection(&condState->waitersCountLock);
469 condState->waitersCount++;
470 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
471 // condState->waitersCount, getThreadId());
472 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800473
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800474 DWORD timeout = INFINITE;
475 if (abstime) {
476 nsecs_t reltime = *abstime - systemTime();
477 if (reltime < 0)
478 reltime = 0;
479 timeout = reltime/1000000;
480 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800481
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800482 // Atomically release the external mutex and wait on the semaphore.
483 DWORD res =
484 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800487
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800488 // Reacquire lock to avoid race conditions.
489 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800490
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800491 // No longer waiting.
492 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800493
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800494 // Check to see if we're the last waiter after a broadcast.
495 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800496
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800497 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
498 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800499
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800500 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800501
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800502 // If we're the last waiter thread during this particular broadcast
503 // then signal broadcast() that we're all awake. It'll drop the
504 // internal mutex.
505 if (lastWaiter) {
506 // Atomically signal the "waitersDone" event and wait until we
507 // can acquire the internal mutex. We want to do this in one step
508 // because it ensures that everybody is in the mutex FIFO before
509 // any thread has a chance to run. Without it, another thread
510 // could wake up, do work, and hop back in ahead of us.
511 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
512 INFINITE, FALSE);
513 } else {
514 // Grab the internal mutex.
515 WaitForSingleObject(condState->internalMutex, INFINITE);
516 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800517
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800518 // Release the internal and grab the external.
519 ReleaseMutex(condState->internalMutex);
520 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800521
Elliott Hughes643268f2018-10-08 11:10:11 -0700522 return res == WAIT_OBJECT_0 ? OK : -1;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800523 }
524} WinCondition;
525
526/*
527 * Constructor. Set up the WinCondition stuff.
528 */
529Condition::Condition()
530{
531 WinCondition* condState = new WinCondition;
532
533 condState->waitersCount = 0;
534 condState->wasBroadcast = false;
535 // semaphore: no security, initial value of 0
536 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
537 InitializeCriticalSection(&condState->waitersCountLock);
538 // auto-reset event, not signaled initially
539 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
540 // used so we don't have to lock external mutex on signal/broadcast
541 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
542
543 mState = condState;
544}
545
546/*
547 * Destructor. Free Windows resources as well as our allocated storage.
548 */
549Condition::~Condition()
550{
551 WinCondition* condState = (WinCondition*) mState;
552 if (condState != NULL) {
553 CloseHandle(condState->sema);
554 CloseHandle(condState->waitersDone);
555 delete condState;
556 }
557}
558
559
560status_t Condition::wait(Mutex& mutex)
561{
562 WinCondition* condState = (WinCondition*) mState;
563 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800564
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800565 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
566}
567
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800568status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
569{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200570 WinCondition* condState = (WinCondition*) mState;
571 HANDLE hMutex = (HANDLE) mutex.mState;
572 nsecs_t absTime = systemTime()+reltime;
573
574 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800575}
576
577/*
578 * Signal the condition variable, allowing one thread to continue.
579 */
580void Condition::signal()
581{
582 WinCondition* condState = (WinCondition*) mState;
583
584 // Lock the internal mutex. This ensures that we don't clash with
585 // broadcast().
586 WaitForSingleObject(condState->internalMutex, INFINITE);
587
588 EnterCriticalSection(&condState->waitersCountLock);
589 bool haveWaiters = (condState->waitersCount > 0);
590 LeaveCriticalSection(&condState->waitersCountLock);
591
592 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
593 // down a notch.
594 if (haveWaiters)
595 ReleaseSemaphore(condState->sema, 1, 0);
596
597 // Release internal mutex.
598 ReleaseMutex(condState->internalMutex);
599}
600
601/*
602 * Signal the condition variable, allowing all threads to continue.
603 *
604 * First we have to wake up all threads waiting on the semaphore, then
605 * we wait until all of the threads have actually been woken before
606 * releasing the internal mutex. This ensures that all threads are woken.
607 */
608void Condition::broadcast()
609{
610 WinCondition* condState = (WinCondition*) mState;
611
612 // Lock the internal mutex. This keeps the guys we're waking up
613 // from getting too far.
614 WaitForSingleObject(condState->internalMutex, INFINITE);
615
616 EnterCriticalSection(&condState->waitersCountLock);
617 bool haveWaiters = false;
618
619 if (condState->waitersCount > 0) {
620 haveWaiters = true;
621 condState->wasBroadcast = true;
622 }
623
624 if (haveWaiters) {
625 // Wake up all the waiters.
626 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
627
628 LeaveCriticalSection(&condState->waitersCountLock);
629
630 // Wait for all awakened threads to acquire the counting semaphore.
631 // The last guy who was waiting sets this.
632 WaitForSingleObject(condState->waitersDone, INFINITE);
633
634 // Reset wasBroadcast. (No crit section needed because nobody
635 // else can wake up to poke at it.)
636 condState->wasBroadcast = 0;
637 } else {
638 // nothing to do
639 LeaveCriticalSection(&condState->waitersCountLock);
640 }
641
642 // Release internal mutex.
643 ReleaseMutex(condState->internalMutex);
644}
645
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800646#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800647
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800648// ----------------------------------------------------------------------------
649
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800650/*
651 * This is our thread object!
652 */
653
654Thread::Thread(bool canCallJava)
Elliott Hughes643268f2018-10-08 11:10:11 -0700655 : mCanCallJava(canCallJava),
656 mThread(thread_id_t(-1)),
657 mLock("Thread::mLock"),
658 mStatus(OK),
659 mExitPending(false),
660 mRunning(false)
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700661#if defined(__ANDROID__)
Elliott Hughes643268f2018-10-08 11:10:11 -0700662 ,
663 mTid(-1)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800664#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800665{
666}
667
668Thread::~Thread()
669{
670}
671
672status_t Thread::readyToRun()
673{
Elliott Hughes643268f2018-10-08 11:10:11 -0700674 return OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800675}
676
677status_t Thread::run(const char* name, int32_t priority, size_t stack)
678{
Brian Carlstrome71b9142016-03-12 16:08:12 -0800679 LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
680
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800681 Mutex::Autolock _l(mLock);
682
683 if (mRunning) {
684 // thread already started
685 return INVALID_OPERATION;
686 }
687
688 // reset status and exitPending to their default value, so we can
689 // try again after an error happened (either below, or in readyToRun())
Elliott Hughes643268f2018-10-08 11:10:11 -0700690 mStatus = OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800691 mExitPending = false;
692 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800693
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800694 // hold a strong reference on ourself
695 mHoldSelf = this;
696
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800697 mRunning = true;
698
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800699 bool res;
700 if (mCanCallJava) {
701 res = createThreadEtc(_threadLoop,
702 this, name, priority, stack, &mThread);
703 } else {
704 res = androidCreateRawThreadEtc(_threadLoop,
705 this, name, priority, stack, &mThread);
706 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800707
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800708 if (res == false) {
709 mStatus = UNKNOWN_ERROR; // something happened!
710 mRunning = false;
711 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800712 mHoldSelf.clear(); // "this" may have gone away after this.
713
714 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800715 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800716
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800717 // Do not refer to mStatus here: The thread is already running (may, in fact
Elliott Hughes643268f2018-10-08 11:10:11 -0700718 // already have exited with a valid mStatus result). The OK indication
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800719 // here merely indicates successfully starting the thread and does not
720 // imply successful termination/execution.
Elliott Hughes643268f2018-10-08 11:10:11 -0700721 return OK;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800722
723 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800724}
725
726int Thread::_threadLoop(void* user)
727{
728 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800729
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800730 sp<Thread> strong(self->mHoldSelf);
731 wp<Thread> weak(strong);
732 self->mHoldSelf.clear();
733
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700734#if defined(__ANDROID__)
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700735 // this is very useful for debugging with gdb
736 self->mTid = gettid();
737#endif
738
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800739 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800740
741 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800742 bool result;
743 if (first) {
744 first = false;
745 self->mStatus = self->readyToRun();
Elliott Hughes643268f2018-10-08 11:10:11 -0700746 result = (self->mStatus == OK);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800747
Glenn Kasten966a48f2011-02-01 11:32:29 -0800748 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800749 // Binder threads (and maybe others) rely on threadLoop
750 // running at least once after a successful ::readyToRun()
751 // (unless, of course, the thread has already been asked to exit
752 // at that point).
753 // This is because threads are essentially used like this:
754 // (new ThreadSubclass())->run();
755 // The caller therefore does not retain a strong reference to
756 // the thread and the thread would simply disappear after the
757 // successful ::readyToRun() call instead of entering the
758 // threadLoop at least once.
759 result = self->threadLoop();
760 }
761 } else {
762 result = self->threadLoop();
763 }
764
Glenn Kasten966a48f2011-02-01 11:32:29 -0800765 // establish a scope for mLock
766 {
767 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800768 if (result == false || self->mExitPending) {
769 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800770 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800771 // clear thread ID so that requestExitAndWait() does not exit if
772 // called by a new thread using the same thread ID as this one.
773 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800774 // note that interested observers blocked in requestExitAndWait are
775 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700776 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800777 break;
778 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800779 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800780
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800781 // Release our strong reference, to let a chance to the thread
782 // to die a peaceful death.
783 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700784 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800785 strong = weak.promote();
Yi Konge1731a42018-07-16 18:11:34 -0700786 } while(strong != nullptr);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800787
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800788 return 0;
789}
790
791void Thread::requestExit()
792{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800793 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800794 mExitPending = true;
795}
796
797status_t Thread::requestExitAndWait()
798{
Glenn Kastena538e262011-06-02 08:59:28 -0700799 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800800 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000801 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800802 "Thread (this=%p): don't call waitForExit() from this "
803 "Thread object's thread. It's a guaranteed deadlock!",
804 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800805
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800806 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800807 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800808
Glenn Kastena538e262011-06-02 08:59:28 -0700809 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800810
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800811 while (mRunning == true) {
812 mThreadExitedCondition.wait(mLock);
813 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800814 // This next line is probably not needed any more, but is being left for
815 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800816 mExitPending = false;
817
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800818 return mStatus;
819}
820
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700821status_t Thread::join()
822{
823 Mutex::Autolock _l(mLock);
824 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000825 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700826 "Thread (this=%p): don't call join() from this "
827 "Thread object's thread. It's a guaranteed deadlock!",
828 this);
829
830 return WOULD_BLOCK;
831 }
832
833 while (mRunning == true) {
834 mThreadExitedCondition.wait(mLock);
835 }
836
837 return mStatus;
838}
839
Romain Guy31ba37f2013-03-11 14:34:56 -0700840bool Thread::isRunning() const {
841 Mutex::Autolock _l(mLock);
842 return mRunning;
843}
844
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700845#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700846pid_t Thread::getTid() const
847{
848 // mTid is not defined until the child initializes it, and the caller may need it earlier
849 Mutex::Autolock _l(mLock);
850 pid_t tid;
851 if (mRunning) {
852 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700853 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700854 } else {
855 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
856 tid = -1;
857 }
858 return tid;
859}
860#endif
861
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800862bool Thread::exitPending() const
863{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800864 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800865 return mExitPending;
866}
867
868
869
870}; // namespace android