blob: 55eadb07a607ff95cbbc89ea1480bf6947b2f209 [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.
Glenn Kastenfe34e452012-04-30 16:03:30 -070089 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
Rick Yiuf7f44422019-12-26 19:35:03 +080090 SetTaskProfiles(0, {"SCHED_SP_BACKGROUND"}, true);
Dianne Hackborna78bab02010-09-09 15:50:18 -070091 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -080092
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080093 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080094 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080095 free(name);
96 }
97 return f(u);
98 }
99};
Rick Yiuf7f44422019-12-26 19:35:03 +0800100#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800101
Mathias Agopian6090df82013-03-07 15:34:28 -0800102void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -0800103#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -0800104 // Mac OS doesn't have this, and we build libutil for the host too
105 int hasAt = 0;
106 int hasDot = 0;
107 const char *s = name;
108 while (*s) {
109 if (*s == '.') hasDot = 1;
110 else if (*s == '@') hasAt = 1;
111 s++;
112 }
113 int len = s - name;
114 if (len < 15 || hasAt || !hasDot) {
115 s = name;
116 } else {
117 s = name + len - 15;
118 }
119 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
120#endif
121}
122
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800123int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
124 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700125 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800126 int32_t threadPriority,
127 size_t threadStackSize,
128 android_thread_id_t *threadId)
129{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800130 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800131 pthread_attr_init(&attr);
132 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
133
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700134#if defined(__ANDROID__) /* valgrind is rejecting RT-priority create reqs */
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800135 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700136 // Now that the pthread_t has a method to find the associated
137 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
138 // this trampoline in some cases as the parent could set the properties
139 // for the child. However, there would be a race condition because the
140 // child becomes ready immediately, and it doesn't work for the name.
141 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
142 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800143 thread_data_t* t = new thread_data_t;
144 t->priority = threadPriority;
145 t->threadName = threadName ? strdup(threadName) : NULL;
146 t->entryFunction = entryFunction;
147 t->userData = userData;
148 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800149 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800150 }
151#endif
152
153 if (threadStackSize) {
154 pthread_attr_setstacksize(&attr, threadStackSize);
155 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800156
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800157 errno = 0;
158 pthread_t thread;
159 int result = pthread_create(&thread, &attr,
160 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700161 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800162 if (result != 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700163 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800164 "(android threadPriority=%d)",
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700165 entryFunction, result, strerror(errno), threadPriority);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800166 return 0;
167 }
168
Glenn Kastena538e262011-06-02 08:59:28 -0700169 // Note that *threadID is directly available to the parent only, as it is
170 // assigned after the child starts. Use memory barrier / lock if the child
171 // or other threads also need access.
Yi Konge1731a42018-07-16 18:11:34 -0700172 if (threadId != nullptr) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800173 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
174 }
175 return 1;
176}
177
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700178#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700179static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
180{
181 return (pthread_t) thread;
182}
183#endif
184
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800185android_thread_id_t androidGetThreadId()
186{
187 return (android_thread_id_t)pthread_self();
188}
189
190// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800191#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800192// ----------------------------------------------------------------------------
193
194/*
195 * Trampoline to make us __stdcall-compliant.
196 *
197 * We're expected to delete "vDetails" when we're done.
198 */
199struct threadDetails {
200 int (*func)(void*);
201 void* arg;
202};
203static __stdcall unsigned int threadIntermediary(void* vDetails)
204{
205 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
206 int result;
207
208 result = (*(pDetails->func))(pDetails->arg);
209
210 delete pDetails;
211
Steve Block8b4cf772011-10-12 17:27:03 +0100212 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800213 return (unsigned int) result;
214}
215
216/*
217 * Create and run a new thread.
218 */
219static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
220{
221 HANDLE hThread;
222 struct threadDetails* pDetails = new threadDetails; // must be on heap
223 unsigned int thrdaddr;
224
225 pDetails->func = fn;
226 pDetails->arg = arg;
227
228#if defined(HAVE__BEGINTHREADEX)
229 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
230 &thrdaddr);
231 if (hThread == 0)
232#elif defined(HAVE_CREATETHREAD)
233 hThread = CreateThread(NULL, 0,
234 (LPTHREAD_START_ROUTINE) threadIntermediary,
235 (void*) pDetails, 0, (DWORD*) &thrdaddr);
236 if (hThread == NULL)
237#endif
238 {
Steve Block8b4cf772011-10-12 17:27:03 +0100239 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800240 return false;
241 }
242
243#if defined(HAVE_CREATETHREAD)
244 /* close the management handle */
245 CloseHandle(hThread);
246#endif
247
248 if (id != NULL) {
249 *id = (android_thread_id_t)thrdaddr;
250 }
251
252 return true;
253}
254
255int androidCreateRawThreadEtc(android_thread_func_t fn,
256 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700257 const char* /*threadName*/,
258 int32_t /*threadPriority*/,
259 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800260 android_thread_id_t *threadId)
261{
262 return doCreateThread( fn, userData, threadId);
263}
264
265android_thread_id_t androidGetThreadId()
266{
267 return (android_thread_id_t)GetCurrentThreadId();
268}
269
270// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800271#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800272
273// ----------------------------------------------------------------------------
274
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800275int androidCreateThread(android_thread_func_t fn, void* arg)
276{
277 return createThreadEtc(fn, arg);
278}
279
280int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
281{
282 return createThreadEtc(fn, arg, "android:unnamed_thread",
283 PRIORITY_DEFAULT, 0, id);
284}
285
286static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
287
288int androidCreateThreadEtc(android_thread_func_t entryFunction,
289 void *userData,
290 const char* threadName,
291 int32_t threadPriority,
292 size_t threadStackSize,
293 android_thread_id_t *threadId)
294{
295 return gCreateThreadFn(entryFunction, userData, threadName,
296 threadPriority, threadStackSize, threadId);
297}
298
299void androidSetCreateThreadFunc(android_create_thread_fn func)
300{
301 gCreateThreadFn = func;
302}
303
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700304#if defined(__ANDROID__)
Greg Kaiserb4730612020-08-24 10:15:47 -0700305namespace {
306int androidSetThreadPriorityInternal(pid_t tid, int pri, bool change_policy) {
Dianne Hackborn235af972009-12-07 17:59:37 -0800307 int rc = 0;
308 int lasterr = 0;
Rick Yiuf7f44422019-12-26 19:35:03 +0800309 int curr_pri = getpriority(PRIO_PROCESS, tid);
310
311 if (curr_pri == pri) {
312 return rc;
313 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800314
Rick Yiu57affbf2020-02-11 14:59:37 +0800315 if (change_policy) {
316 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
317 rc = SetTaskProfiles(tid, {"SCHED_SP_BACKGROUND"}, true) ? 0 : -1;
318 } else if (curr_pri >= ANDROID_PRIORITY_BACKGROUND) {
319 SchedPolicy policy = SP_FOREGROUND;
320 // Change to the sched policy group of the process.
321 get_sched_policy(getpid(), &policy);
322 rc = SetTaskProfiles(tid, {get_sched_policy_profile_name(policy)}, true) ? 0 : -1;
323 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800324
Rick Yiu57affbf2020-02-11 14:59:37 +0800325 if (rc) {
326 lasterr = errno;
327 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800328 }
329
330 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
331 rc = INVALID_OPERATION;
332 } else {
333 errno = lasterr;
334 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800335
Dianne Hackborn235af972009-12-07 17:59:37 -0800336 return rc;
337}
Greg Kaiserb4730612020-08-24 10:15:47 -0700338} // namespace
339
340int androidSetThreadPriority(pid_t tid, int pri) {
341 return androidSetThreadPriorityInternal(tid, pri, true);
342}
343
344int androidSetThreadPriorityAndPolicy(pid_t tid, int pri, bool change_policy) {
345 return androidSetThreadPriorityInternal(tid, pri, change_policy);
346}
Dianne Hackborn235af972009-12-07 17:59:37 -0800347
Andreas Huber8ddbed92011-09-15 12:21:40 -0700348int androidGetThreadPriority(pid_t tid) {
349 return getpriority(PRIO_PROCESS, tid);
350}
351
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700352#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700353
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800354namespace android {
355
356/*
357 * ===========================================================================
358 * Mutex class
359 * ===========================================================================
360 */
361
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800362#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700363// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800364#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800365
366Mutex::Mutex()
367{
368 HANDLE hMutex;
369
370 assert(sizeof(hMutex) == sizeof(mState));
371
372 hMutex = CreateMutex(NULL, FALSE, NULL);
373 mState = (void*) hMutex;
374}
375
Dan Willemsen528f1442017-11-29 18:06:11 -0800376Mutex::Mutex(const char* /*name*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800377{
378 // XXX: name not used for now
379 HANDLE hMutex;
380
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200381 assert(sizeof(hMutex) == sizeof(mState));
382
383 hMutex = CreateMutex(NULL, FALSE, NULL);
384 mState = (void*) hMutex;
385}
386
Dan Willemsen528f1442017-11-29 18:06:11 -0800387Mutex::Mutex(int /*type*/, const char* /*name*/)
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200388{
389 // XXX: type and name not used for now
390 HANDLE hMutex;
391
392 assert(sizeof(hMutex) == sizeof(mState));
393
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800394 hMutex = CreateMutex(NULL, FALSE, NULL);
395 mState = (void*) hMutex;
396}
397
398Mutex::~Mutex()
399{
400 CloseHandle((HANDLE) mState);
401}
402
403status_t Mutex::lock()
404{
405 DWORD dwWaitResult;
406 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
Elliott Hughes643268f2018-10-08 11:10:11 -0700407 return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800408}
409
410void Mutex::unlock()
411{
412 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100413 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800414}
415
416status_t Mutex::tryLock()
417{
418 DWORD dwWaitResult;
419
420 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
421 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100422 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800423 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
424}
425
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800426#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800427
428
429/*
430 * ===========================================================================
431 * Condition class
432 * ===========================================================================
433 */
434
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800435#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700436// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800437#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800438
439/*
440 * Windows doesn't have a condition variable solution. It's possible
441 * to create one, but it's easy to get it wrong. For a discussion, and
442 * the origin of this implementation, see:
443 *
444 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
445 *
446 * The implementation shown on the page does NOT follow POSIX semantics.
447 * As an optimization they require acquiring the external mutex before
448 * calling signal() and broadcast(), whereas POSIX only requires grabbing
449 * it before calling wait(). The implementation here has been un-optimized
450 * to have the correct behavior.
451 */
452typedef struct WinCondition {
453 // Number of waiting threads.
454 int waitersCount;
455
456 // Serialize access to waitersCount.
457 CRITICAL_SECTION waitersCountLock;
458
459 // Semaphore used to queue up threads waiting for the condition to
460 // become signaled.
461 HANDLE sema;
462
463 // An auto-reset event used by the broadcast/signal thread to wait
464 // for all the waiting thread(s) to wake up and be released from
465 // the semaphore.
466 HANDLE waitersDone;
467
468 // This mutex wouldn't be necessary if we required that the caller
469 // lock the external mutex before calling signal() and broadcast().
470 // I'm trying to mimic pthread semantics though.
471 HANDLE internalMutex;
472
473 // Keeps track of whether we were broadcasting or signaling. This
474 // allows us to optimize the code if we're just signaling.
475 bool wasBroadcast;
476
477 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
478 {
479 // Increment the wait count, avoiding race conditions.
480 EnterCriticalSection(&condState->waitersCountLock);
481 condState->waitersCount++;
482 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
483 // condState->waitersCount, getThreadId());
484 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486 DWORD timeout = INFINITE;
487 if (abstime) {
488 nsecs_t reltime = *abstime - systemTime();
489 if (reltime < 0)
490 reltime = 0;
491 timeout = reltime/1000000;
492 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800493
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800494 // Atomically release the external mutex and wait on the semaphore.
495 DWORD res =
496 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800497
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800498 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800499
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800500 // Reacquire lock to avoid race conditions.
501 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800502
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800503 // No longer waiting.
504 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800505
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800506 // Check to see if we're the last waiter after a broadcast.
507 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800508
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800509 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
510 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800511
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800512 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800513
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800514 // If we're the last waiter thread during this particular broadcast
515 // then signal broadcast() that we're all awake. It'll drop the
516 // internal mutex.
517 if (lastWaiter) {
518 // Atomically signal the "waitersDone" event and wait until we
519 // can acquire the internal mutex. We want to do this in one step
520 // because it ensures that everybody is in the mutex FIFO before
521 // any thread has a chance to run. Without it, another thread
522 // could wake up, do work, and hop back in ahead of us.
523 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
524 INFINITE, FALSE);
525 } else {
526 // Grab the internal mutex.
527 WaitForSingleObject(condState->internalMutex, INFINITE);
528 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800529
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800530 // Release the internal and grab the external.
531 ReleaseMutex(condState->internalMutex);
532 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800533
Elliott Hughes643268f2018-10-08 11:10:11 -0700534 return res == WAIT_OBJECT_0 ? OK : -1;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800535 }
536} WinCondition;
537
538/*
539 * Constructor. Set up the WinCondition stuff.
540 */
541Condition::Condition()
542{
543 WinCondition* condState = new WinCondition;
544
545 condState->waitersCount = 0;
546 condState->wasBroadcast = false;
547 // semaphore: no security, initial value of 0
548 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
549 InitializeCriticalSection(&condState->waitersCountLock);
550 // auto-reset event, not signaled initially
551 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
552 // used so we don't have to lock external mutex on signal/broadcast
553 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
554
555 mState = condState;
556}
557
558/*
559 * Destructor. Free Windows resources as well as our allocated storage.
560 */
561Condition::~Condition()
562{
563 WinCondition* condState = (WinCondition*) mState;
564 if (condState != NULL) {
565 CloseHandle(condState->sema);
566 CloseHandle(condState->waitersDone);
567 delete condState;
568 }
569}
570
571
572status_t Condition::wait(Mutex& mutex)
573{
574 WinCondition* condState = (WinCondition*) mState;
575 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800576
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800577 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
578}
579
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800580status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
581{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200582 WinCondition* condState = (WinCondition*) mState;
583 HANDLE hMutex = (HANDLE) mutex.mState;
584 nsecs_t absTime = systemTime()+reltime;
585
586 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800587}
588
589/*
590 * Signal the condition variable, allowing one thread to continue.
591 */
592void Condition::signal()
593{
594 WinCondition* condState = (WinCondition*) mState;
595
596 // Lock the internal mutex. This ensures that we don't clash with
597 // broadcast().
598 WaitForSingleObject(condState->internalMutex, INFINITE);
599
600 EnterCriticalSection(&condState->waitersCountLock);
601 bool haveWaiters = (condState->waitersCount > 0);
602 LeaveCriticalSection(&condState->waitersCountLock);
603
604 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
605 // down a notch.
606 if (haveWaiters)
607 ReleaseSemaphore(condState->sema, 1, 0);
608
609 // Release internal mutex.
610 ReleaseMutex(condState->internalMutex);
611}
612
613/*
614 * Signal the condition variable, allowing all threads to continue.
615 *
616 * First we have to wake up all threads waiting on the semaphore, then
617 * we wait until all of the threads have actually been woken before
618 * releasing the internal mutex. This ensures that all threads are woken.
619 */
620void Condition::broadcast()
621{
622 WinCondition* condState = (WinCondition*) mState;
623
624 // Lock the internal mutex. This keeps the guys we're waking up
625 // from getting too far.
626 WaitForSingleObject(condState->internalMutex, INFINITE);
627
628 EnterCriticalSection(&condState->waitersCountLock);
629 bool haveWaiters = false;
630
631 if (condState->waitersCount > 0) {
632 haveWaiters = true;
633 condState->wasBroadcast = true;
634 }
635
636 if (haveWaiters) {
637 // Wake up all the waiters.
638 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
639
640 LeaveCriticalSection(&condState->waitersCountLock);
641
642 // Wait for all awakened threads to acquire the counting semaphore.
643 // The last guy who was waiting sets this.
644 WaitForSingleObject(condState->waitersDone, INFINITE);
645
646 // Reset wasBroadcast. (No crit section needed because nobody
647 // else can wake up to poke at it.)
648 condState->wasBroadcast = 0;
649 } else {
650 // nothing to do
651 LeaveCriticalSection(&condState->waitersCountLock);
652 }
653
654 // Release internal mutex.
655 ReleaseMutex(condState->internalMutex);
656}
657
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800658#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800659
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800660// ----------------------------------------------------------------------------
661
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800662/*
663 * This is our thread object!
664 */
665
666Thread::Thread(bool canCallJava)
Elliott Hughes643268f2018-10-08 11:10:11 -0700667 : mCanCallJava(canCallJava),
668 mThread(thread_id_t(-1)),
669 mLock("Thread::mLock"),
670 mStatus(OK),
671 mExitPending(false),
672 mRunning(false)
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700673#if defined(__ANDROID__)
Elliott Hughes643268f2018-10-08 11:10:11 -0700674 ,
675 mTid(-1)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800676#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800677{
678}
679
680Thread::~Thread()
681{
682}
683
684status_t Thread::readyToRun()
685{
Elliott Hughes643268f2018-10-08 11:10:11 -0700686 return OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800687}
688
689status_t Thread::run(const char* name, int32_t priority, size_t stack)
690{
Brian Carlstrome71b9142016-03-12 16:08:12 -0800691 LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
692
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800693 Mutex::Autolock _l(mLock);
694
695 if (mRunning) {
696 // thread already started
697 return INVALID_OPERATION;
698 }
699
700 // reset status and exitPending to their default value, so we can
701 // try again after an error happened (either below, or in readyToRun())
Elliott Hughes643268f2018-10-08 11:10:11 -0700702 mStatus = OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800703 mExitPending = false;
704 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800705
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800706 // hold a strong reference on ourself
707 mHoldSelf = this;
708
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800709 mRunning = true;
710
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800711 bool res;
712 if (mCanCallJava) {
713 res = createThreadEtc(_threadLoop,
714 this, name, priority, stack, &mThread);
715 } else {
716 res = androidCreateRawThreadEtc(_threadLoop,
717 this, name, priority, stack, &mThread);
718 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800719
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800720 if (res == false) {
721 mStatus = UNKNOWN_ERROR; // something happened!
722 mRunning = false;
723 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800724 mHoldSelf.clear(); // "this" may have gone away after this.
725
726 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800727 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800728
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800729 // Do not refer to mStatus here: The thread is already running (may, in fact
Elliott Hughes643268f2018-10-08 11:10:11 -0700730 // already have exited with a valid mStatus result). The OK indication
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800731 // here merely indicates successfully starting the thread and does not
732 // imply successful termination/execution.
Elliott Hughes643268f2018-10-08 11:10:11 -0700733 return OK;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800734
735 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800736}
737
738int Thread::_threadLoop(void* user)
739{
740 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800741
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800742 sp<Thread> strong(self->mHoldSelf);
743 wp<Thread> weak(strong);
744 self->mHoldSelf.clear();
745
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700746#if defined(__ANDROID__)
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700747 // this is very useful for debugging with gdb
748 self->mTid = gettid();
749#endif
750
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800751 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800752
753 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800754 bool result;
755 if (first) {
756 first = false;
757 self->mStatus = self->readyToRun();
Elliott Hughes643268f2018-10-08 11:10:11 -0700758 result = (self->mStatus == OK);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800759
Glenn Kasten966a48f2011-02-01 11:32:29 -0800760 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800761 // Binder threads (and maybe others) rely on threadLoop
762 // running at least once after a successful ::readyToRun()
763 // (unless, of course, the thread has already been asked to exit
764 // at that point).
765 // This is because threads are essentially used like this:
766 // (new ThreadSubclass())->run();
767 // The caller therefore does not retain a strong reference to
768 // the thread and the thread would simply disappear after the
769 // successful ::readyToRun() call instead of entering the
770 // threadLoop at least once.
771 result = self->threadLoop();
772 }
773 } else {
774 result = self->threadLoop();
775 }
776
Glenn Kasten966a48f2011-02-01 11:32:29 -0800777 // establish a scope for mLock
778 {
779 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800780 if (result == false || self->mExitPending) {
781 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800782 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800783 // clear thread ID so that requestExitAndWait() does not exit if
784 // called by a new thread using the same thread ID as this one.
785 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800786 // note that interested observers blocked in requestExitAndWait are
787 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700788 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800789 break;
790 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800791 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800792
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800793 // Release our strong reference, to let a chance to the thread
794 // to die a peaceful death.
795 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700796 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800797 strong = weak.promote();
Yi Konge1731a42018-07-16 18:11:34 -0700798 } while(strong != nullptr);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800799
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800800 return 0;
801}
802
803void Thread::requestExit()
804{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800805 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800806 mExitPending = true;
807}
808
809status_t Thread::requestExitAndWait()
810{
Glenn Kastena538e262011-06-02 08:59:28 -0700811 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800812 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000813 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800814 "Thread (this=%p): don't call waitForExit() from this "
815 "Thread object's thread. It's a guaranteed deadlock!",
816 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800817
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800818 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800819 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800820
Glenn Kastena538e262011-06-02 08:59:28 -0700821 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800822
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800823 while (mRunning == true) {
824 mThreadExitedCondition.wait(mLock);
825 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800826 // This next line is probably not needed any more, but is being left for
827 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800828 mExitPending = false;
829
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800830 return mStatus;
831}
832
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700833status_t Thread::join()
834{
835 Mutex::Autolock _l(mLock);
836 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000837 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700838 "Thread (this=%p): don't call join() from this "
839 "Thread object's thread. It's a guaranteed deadlock!",
840 this);
841
842 return WOULD_BLOCK;
843 }
844
845 while (mRunning == true) {
846 mThreadExitedCondition.wait(mLock);
847 }
848
849 return mStatus;
850}
851
Romain Guy31ba37f2013-03-11 14:34:56 -0700852bool Thread::isRunning() const {
853 Mutex::Autolock _l(mLock);
854 return mRunning;
855}
856
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700857#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700858pid_t Thread::getTid() const
859{
860 // mTid is not defined until the child initializes it, and the caller may need it earlier
861 Mutex::Autolock _l(mLock);
862 pid_t tid;
863 if (mRunning) {
864 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700865 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700866 } else {
867 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
868 tid = -1;
869 }
870 return tid;
871}
872#endif
873
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800874bool Thread::exitPending() const
875{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800876 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800877 return mExitPending;
878}
879
880
881
882}; // namespace android