blob: a85ff20bc7c7f8a119a23971855312a8f3a2a700 [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
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080087 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080088 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080089 free(name);
90 }
91 return f(u);
92 }
93};
Rick Yiuf7f44422019-12-26 19:35:03 +080094#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080095
Mathias Agopian6090df82013-03-07 15:34:28 -080096void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -080097#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -080098 // Mac OS doesn't have this, and we build libutil for the host too
99 int hasAt = 0;
100 int hasDot = 0;
101 const char *s = name;
102 while (*s) {
103 if (*s == '.') hasDot = 1;
104 else if (*s == '@') hasAt = 1;
105 s++;
106 }
107 int len = s - name;
108 if (len < 15 || hasAt || !hasDot) {
109 s = name;
110 } else {
111 s = name + len - 15;
112 }
113 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
114#endif
115}
116
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800117int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
118 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700119 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800120 int32_t threadPriority,
121 size_t threadStackSize,
122 android_thread_id_t *threadId)
123{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800124 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800125 pthread_attr_init(&attr);
126 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
127
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700128#if defined(__ANDROID__) /* valgrind is rejecting RT-priority create reqs */
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800129 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700130 // Now that the pthread_t has a method to find the associated
131 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
132 // this trampoline in some cases as the parent could set the properties
133 // for the child. However, there would be a race condition because the
134 // child becomes ready immediately, and it doesn't work for the name.
135 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
136 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800137 thread_data_t* t = new thread_data_t;
138 t->priority = threadPriority;
139 t->threadName = threadName ? strdup(threadName) : NULL;
140 t->entryFunction = entryFunction;
141 t->userData = userData;
142 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800143 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800144 }
145#endif
146
147 if (threadStackSize) {
148 pthread_attr_setstacksize(&attr, threadStackSize);
149 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800150
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800151 errno = 0;
152 pthread_t thread;
153 int result = pthread_create(&thread, &attr,
154 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700155 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800156 if (result != 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700157 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800158 "(android threadPriority=%d)",
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700159 entryFunction, result, strerror(errno), threadPriority);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800160 return 0;
161 }
162
Glenn Kastena538e262011-06-02 08:59:28 -0700163 // Note that *threadID is directly available to the parent only, as it is
164 // assigned after the child starts. Use memory barrier / lock if the child
165 // or other threads also need access.
Yi Konge1731a42018-07-16 18:11:34 -0700166 if (threadId != nullptr) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800167 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
168 }
169 return 1;
170}
171
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700172#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700173static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
174{
175 return (pthread_t) thread;
176}
177#endif
178
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800179android_thread_id_t androidGetThreadId()
180{
181 return (android_thread_id_t)pthread_self();
182}
183
184// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800185#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800186// ----------------------------------------------------------------------------
187
188/*
189 * Trampoline to make us __stdcall-compliant.
190 *
191 * We're expected to delete "vDetails" when we're done.
192 */
193struct threadDetails {
194 int (*func)(void*);
195 void* arg;
196};
197static __stdcall unsigned int threadIntermediary(void* vDetails)
198{
199 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
200 int result;
201
202 result = (*(pDetails->func))(pDetails->arg);
203
204 delete pDetails;
205
Steve Block8b4cf772011-10-12 17:27:03 +0100206 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800207 return (unsigned int) result;
208}
209
210/*
211 * Create and run a new thread.
212 */
213static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
214{
215 HANDLE hThread;
216 struct threadDetails* pDetails = new threadDetails; // must be on heap
217 unsigned int thrdaddr;
218
219 pDetails->func = fn;
220 pDetails->arg = arg;
221
222#if defined(HAVE__BEGINTHREADEX)
223 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
224 &thrdaddr);
225 if (hThread == 0)
226#elif defined(HAVE_CREATETHREAD)
227 hThread = CreateThread(NULL, 0,
228 (LPTHREAD_START_ROUTINE) threadIntermediary,
229 (void*) pDetails, 0, (DWORD*) &thrdaddr);
230 if (hThread == NULL)
231#endif
232 {
Steve Block8b4cf772011-10-12 17:27:03 +0100233 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800234 return false;
235 }
236
237#if defined(HAVE_CREATETHREAD)
238 /* close the management handle */
239 CloseHandle(hThread);
240#endif
241
242 if (id != NULL) {
243 *id = (android_thread_id_t)thrdaddr;
244 }
245
246 return true;
247}
248
249int androidCreateRawThreadEtc(android_thread_func_t fn,
250 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700251 const char* /*threadName*/,
252 int32_t /*threadPriority*/,
253 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800254 android_thread_id_t *threadId)
255{
256 return doCreateThread( fn, userData, threadId);
257}
258
259android_thread_id_t androidGetThreadId()
260{
261 return (android_thread_id_t)GetCurrentThreadId();
262}
263
264// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800265#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800266
267// ----------------------------------------------------------------------------
268
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800269int androidCreateThread(android_thread_func_t fn, void* arg)
270{
271 return createThreadEtc(fn, arg);
272}
273
274int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
275{
276 return createThreadEtc(fn, arg, "android:unnamed_thread",
277 PRIORITY_DEFAULT, 0, id);
278}
279
280static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
281
282int androidCreateThreadEtc(android_thread_func_t entryFunction,
283 void *userData,
284 const char* threadName,
285 int32_t threadPriority,
286 size_t threadStackSize,
287 android_thread_id_t *threadId)
288{
289 return gCreateThreadFn(entryFunction, userData, threadName,
290 threadPriority, threadStackSize, threadId);
291}
292
293void androidSetCreateThreadFunc(android_create_thread_fn func)
294{
295 gCreateThreadFn = func;
296}
297
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700298#if defined(__ANDROID__)
Rick Yiufa02bb92020-09-27 11:21:11 +0800299int androidSetThreadPriority(pid_t tid, int pri)
300{
Dianne Hackborn235af972009-12-07 17:59:37 -0800301 int rc = 0;
302 int lasterr = 0;
Rick Yiuf7f44422019-12-26 19:35:03 +0800303 int curr_pri = getpriority(PRIO_PROCESS, tid);
304
305 if (curr_pri == pri) {
306 return rc;
307 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800308
Rick Yiufa02bb92020-09-27 11:21:11 +0800309 if (rc) {
310 lasterr = errno;
Dianne Hackborn235af972009-12-07 17:59:37 -0800311 }
312
313 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
314 rc = INVALID_OPERATION;
315 } else {
316 errno = lasterr;
317 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800318
Dianne Hackborn235af972009-12-07 17:59:37 -0800319 return rc;
320}
321
Andreas Huber8ddbed92011-09-15 12:21:40 -0700322int androidGetThreadPriority(pid_t tid) {
323 return getpriority(PRIO_PROCESS, tid);
324}
325
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700326#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700327
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800328namespace android {
329
330/*
331 * ===========================================================================
332 * Mutex class
333 * ===========================================================================
334 */
335
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800336#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700337// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800338#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800339
340Mutex::Mutex()
341{
342 HANDLE hMutex;
343
344 assert(sizeof(hMutex) == sizeof(mState));
345
346 hMutex = CreateMutex(NULL, FALSE, NULL);
347 mState = (void*) hMutex;
348}
349
Dan Willemsen528f1442017-11-29 18:06:11 -0800350Mutex::Mutex(const char* /*name*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800351{
352 // XXX: name not used for now
353 HANDLE hMutex;
354
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200355 assert(sizeof(hMutex) == sizeof(mState));
356
357 hMutex = CreateMutex(NULL, FALSE, NULL);
358 mState = (void*) hMutex;
359}
360
Dan Willemsen528f1442017-11-29 18:06:11 -0800361Mutex::Mutex(int /*type*/, const char* /*name*/)
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200362{
363 // XXX: type and name not used for now
364 HANDLE hMutex;
365
366 assert(sizeof(hMutex) == sizeof(mState));
367
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800368 hMutex = CreateMutex(NULL, FALSE, NULL);
369 mState = (void*) hMutex;
370}
371
372Mutex::~Mutex()
373{
374 CloseHandle((HANDLE) mState);
375}
376
377status_t Mutex::lock()
378{
379 DWORD dwWaitResult;
380 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
Elliott Hughes643268f2018-10-08 11:10:11 -0700381 return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800382}
383
384void Mutex::unlock()
385{
386 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100387 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800388}
389
390status_t Mutex::tryLock()
391{
392 DWORD dwWaitResult;
393
394 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
395 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100396 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800397 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
398}
399
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800400#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800401
402
403/*
404 * ===========================================================================
405 * Condition class
406 * ===========================================================================
407 */
408
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800409#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700410// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800411#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800412
413/*
414 * Windows doesn't have a condition variable solution. It's possible
415 * to create one, but it's easy to get it wrong. For a discussion, and
416 * the origin of this implementation, see:
417 *
418 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
419 *
420 * The implementation shown on the page does NOT follow POSIX semantics.
421 * As an optimization they require acquiring the external mutex before
422 * calling signal() and broadcast(), whereas POSIX only requires grabbing
423 * it before calling wait(). The implementation here has been un-optimized
424 * to have the correct behavior.
425 */
426typedef struct WinCondition {
427 // Number of waiting threads.
428 int waitersCount;
429
430 // Serialize access to waitersCount.
431 CRITICAL_SECTION waitersCountLock;
432
433 // Semaphore used to queue up threads waiting for the condition to
434 // become signaled.
435 HANDLE sema;
436
437 // An auto-reset event used by the broadcast/signal thread to wait
438 // for all the waiting thread(s) to wake up and be released from
439 // the semaphore.
440 HANDLE waitersDone;
441
442 // This mutex wouldn't be necessary if we required that the caller
443 // lock the external mutex before calling signal() and broadcast().
444 // I'm trying to mimic pthread semantics though.
445 HANDLE internalMutex;
446
447 // Keeps track of whether we were broadcasting or signaling. This
448 // allows us to optimize the code if we're just signaling.
449 bool wasBroadcast;
450
451 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
452 {
453 // Increment the wait count, avoiding race conditions.
454 EnterCriticalSection(&condState->waitersCountLock);
455 condState->waitersCount++;
456 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
457 // condState->waitersCount, getThreadId());
458 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800459
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800460 DWORD timeout = INFINITE;
461 if (abstime) {
462 nsecs_t reltime = *abstime - systemTime();
463 if (reltime < 0)
464 reltime = 0;
465 timeout = reltime/1000000;
466 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800467
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800468 // Atomically release the external mutex and wait on the semaphore.
469 DWORD res =
470 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800471
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800472 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800473
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800474 // Reacquire lock to avoid race conditions.
475 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800476
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800477 // No longer waiting.
478 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800479
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800480 // Check to see if we're the last waiter after a broadcast.
481 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800482
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800483 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
484 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800487
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800488 // If we're the last waiter thread during this particular broadcast
489 // then signal broadcast() that we're all awake. It'll drop the
490 // internal mutex.
491 if (lastWaiter) {
492 // Atomically signal the "waitersDone" event and wait until we
493 // can acquire the internal mutex. We want to do this in one step
494 // because it ensures that everybody is in the mutex FIFO before
495 // any thread has a chance to run. Without it, another thread
496 // could wake up, do work, and hop back in ahead of us.
497 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
498 INFINITE, FALSE);
499 } else {
500 // Grab the internal mutex.
501 WaitForSingleObject(condState->internalMutex, INFINITE);
502 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800503
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800504 // Release the internal and grab the external.
505 ReleaseMutex(condState->internalMutex);
506 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800507
Elliott Hughes643268f2018-10-08 11:10:11 -0700508 return res == WAIT_OBJECT_0 ? OK : -1;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800509 }
510} WinCondition;
511
512/*
513 * Constructor. Set up the WinCondition stuff.
514 */
515Condition::Condition()
516{
517 WinCondition* condState = new WinCondition;
518
519 condState->waitersCount = 0;
520 condState->wasBroadcast = false;
521 // semaphore: no security, initial value of 0
522 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
523 InitializeCriticalSection(&condState->waitersCountLock);
524 // auto-reset event, not signaled initially
525 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
526 // used so we don't have to lock external mutex on signal/broadcast
527 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
528
529 mState = condState;
530}
531
532/*
533 * Destructor. Free Windows resources as well as our allocated storage.
534 */
535Condition::~Condition()
536{
537 WinCondition* condState = (WinCondition*) mState;
538 if (condState != NULL) {
539 CloseHandle(condState->sema);
540 CloseHandle(condState->waitersDone);
541 delete condState;
542 }
543}
544
545
546status_t Condition::wait(Mutex& mutex)
547{
548 WinCondition* condState = (WinCondition*) mState;
549 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800550
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800551 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
552}
553
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800554status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
555{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200556 WinCondition* condState = (WinCondition*) mState;
557 HANDLE hMutex = (HANDLE) mutex.mState;
558 nsecs_t absTime = systemTime()+reltime;
559
560 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800561}
562
563/*
564 * Signal the condition variable, allowing one thread to continue.
565 */
566void Condition::signal()
567{
568 WinCondition* condState = (WinCondition*) mState;
569
570 // Lock the internal mutex. This ensures that we don't clash with
571 // broadcast().
572 WaitForSingleObject(condState->internalMutex, INFINITE);
573
574 EnterCriticalSection(&condState->waitersCountLock);
575 bool haveWaiters = (condState->waitersCount > 0);
576 LeaveCriticalSection(&condState->waitersCountLock);
577
578 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
579 // down a notch.
580 if (haveWaiters)
581 ReleaseSemaphore(condState->sema, 1, 0);
582
583 // Release internal mutex.
584 ReleaseMutex(condState->internalMutex);
585}
586
587/*
588 * Signal the condition variable, allowing all threads to continue.
589 *
590 * First we have to wake up all threads waiting on the semaphore, then
591 * we wait until all of the threads have actually been woken before
592 * releasing the internal mutex. This ensures that all threads are woken.
593 */
594void Condition::broadcast()
595{
596 WinCondition* condState = (WinCondition*) mState;
597
598 // Lock the internal mutex. This keeps the guys we're waking up
599 // from getting too far.
600 WaitForSingleObject(condState->internalMutex, INFINITE);
601
602 EnterCriticalSection(&condState->waitersCountLock);
603 bool haveWaiters = false;
604
605 if (condState->waitersCount > 0) {
606 haveWaiters = true;
607 condState->wasBroadcast = true;
608 }
609
610 if (haveWaiters) {
611 // Wake up all the waiters.
612 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
613
614 LeaveCriticalSection(&condState->waitersCountLock);
615
616 // Wait for all awakened threads to acquire the counting semaphore.
617 // The last guy who was waiting sets this.
618 WaitForSingleObject(condState->waitersDone, INFINITE);
619
620 // Reset wasBroadcast. (No crit section needed because nobody
621 // else can wake up to poke at it.)
622 condState->wasBroadcast = 0;
623 } else {
624 // nothing to do
625 LeaveCriticalSection(&condState->waitersCountLock);
626 }
627
628 // Release internal mutex.
629 ReleaseMutex(condState->internalMutex);
630}
631
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800632#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800633
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800634// ----------------------------------------------------------------------------
635
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800636/*
637 * This is our thread object!
638 */
639
640Thread::Thread(bool canCallJava)
Elliott Hughes643268f2018-10-08 11:10:11 -0700641 : mCanCallJava(canCallJava),
642 mThread(thread_id_t(-1)),
643 mLock("Thread::mLock"),
644 mStatus(OK),
645 mExitPending(false),
646 mRunning(false)
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700647#if defined(__ANDROID__)
Elliott Hughes643268f2018-10-08 11:10:11 -0700648 ,
649 mTid(-1)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800650#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800651{
652}
653
654Thread::~Thread()
655{
656}
657
658status_t Thread::readyToRun()
659{
Elliott Hughes643268f2018-10-08 11:10:11 -0700660 return OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800661}
662
663status_t Thread::run(const char* name, int32_t priority, size_t stack)
664{
Brian Carlstrome71b9142016-03-12 16:08:12 -0800665 LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
666
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800667 Mutex::Autolock _l(mLock);
668
669 if (mRunning) {
670 // thread already started
671 return INVALID_OPERATION;
672 }
673
674 // reset status and exitPending to their default value, so we can
675 // try again after an error happened (either below, or in readyToRun())
Elliott Hughes643268f2018-10-08 11:10:11 -0700676 mStatus = OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800677 mExitPending = false;
678 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800679
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800680 // hold a strong reference on ourself
681 mHoldSelf = this;
682
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800683 mRunning = true;
684
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800685 bool res;
686 if (mCanCallJava) {
687 res = createThreadEtc(_threadLoop,
688 this, name, priority, stack, &mThread);
689 } else {
690 res = androidCreateRawThreadEtc(_threadLoop,
691 this, name, priority, stack, &mThread);
692 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800693
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800694 if (res == false) {
695 mStatus = UNKNOWN_ERROR; // something happened!
696 mRunning = false;
697 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800698 mHoldSelf.clear(); // "this" may have gone away after this.
699
700 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800701 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800702
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800703 // Do not refer to mStatus here: The thread is already running (may, in fact
Elliott Hughes643268f2018-10-08 11:10:11 -0700704 // already have exited with a valid mStatus result). The OK indication
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800705 // here merely indicates successfully starting the thread and does not
706 // imply successful termination/execution.
Elliott Hughes643268f2018-10-08 11:10:11 -0700707 return OK;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800708
709 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800710}
711
712int Thread::_threadLoop(void* user)
713{
714 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800715
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800716 sp<Thread> strong(self->mHoldSelf);
717 wp<Thread> weak(strong);
718 self->mHoldSelf.clear();
719
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700720#if defined(__ANDROID__)
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700721 // this is very useful for debugging with gdb
722 self->mTid = gettid();
723#endif
724
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800725 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800726
727 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800728 bool result;
729 if (first) {
730 first = false;
731 self->mStatus = self->readyToRun();
Elliott Hughes643268f2018-10-08 11:10:11 -0700732 result = (self->mStatus == OK);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800733
Glenn Kasten966a48f2011-02-01 11:32:29 -0800734 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800735 // Binder threads (and maybe others) rely on threadLoop
736 // running at least once after a successful ::readyToRun()
737 // (unless, of course, the thread has already been asked to exit
738 // at that point).
739 // This is because threads are essentially used like this:
740 // (new ThreadSubclass())->run();
741 // The caller therefore does not retain a strong reference to
742 // the thread and the thread would simply disappear after the
743 // successful ::readyToRun() call instead of entering the
744 // threadLoop at least once.
745 result = self->threadLoop();
746 }
747 } else {
748 result = self->threadLoop();
749 }
750
Glenn Kasten966a48f2011-02-01 11:32:29 -0800751 // establish a scope for mLock
752 {
753 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800754 if (result == false || self->mExitPending) {
755 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800756 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800757 // clear thread ID so that requestExitAndWait() does not exit if
758 // called by a new thread using the same thread ID as this one.
759 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800760 // note that interested observers blocked in requestExitAndWait are
761 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700762 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800763 break;
764 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800765 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800766
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800767 // Release our strong reference, to let a chance to the thread
768 // to die a peaceful death.
769 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700770 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800771 strong = weak.promote();
Yi Konge1731a42018-07-16 18:11:34 -0700772 } while(strong != nullptr);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800773
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800774 return 0;
775}
776
777void Thread::requestExit()
778{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800779 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800780 mExitPending = true;
781}
782
783status_t Thread::requestExitAndWait()
784{
Glenn Kastena538e262011-06-02 08:59:28 -0700785 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800786 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000787 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800788 "Thread (this=%p): don't call waitForExit() from this "
789 "Thread object's thread. It's a guaranteed deadlock!",
790 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800791
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800792 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800793 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800794
Glenn Kastena538e262011-06-02 08:59:28 -0700795 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800796
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800797 while (mRunning == true) {
798 mThreadExitedCondition.wait(mLock);
799 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800800 // This next line is probably not needed any more, but is being left for
801 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800802 mExitPending = false;
803
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800804 return mStatus;
805}
806
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700807status_t Thread::join()
808{
809 Mutex::Autolock _l(mLock);
810 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000811 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700812 "Thread (this=%p): don't call join() from this "
813 "Thread object's thread. It's a guaranteed deadlock!",
814 this);
815
816 return WOULD_BLOCK;
817 }
818
819 while (mRunning == true) {
820 mThreadExitedCondition.wait(mLock);
821 }
822
823 return mStatus;
824}
825
Romain Guy31ba37f2013-03-11 14:34:56 -0700826bool Thread::isRunning() const {
827 Mutex::Autolock _l(mLock);
828 return mRunning;
829}
830
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700831#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700832pid_t Thread::getTid() const
833{
834 // mTid is not defined until the child initializes it, and the caller may need it earlier
835 Mutex::Autolock _l(mLock);
836 pid_t tid;
837 if (mRunning) {
838 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700839 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700840 } else {
841 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
842 tid = -1;
843 }
844 return tid;
845}
846#endif
847
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800848bool Thread::exitPending() const
849{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800850 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800851 return mExitPending;
852}
853
854
855
856}; // namespace android