blob: eb964978e441a53c797e75ad5ca52c28d8734dda [file] [log] [blame]
The Android Open Source Projectedbf3b62009-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 Project9adf84a2009-03-05 14:34:35 -080017// #define LOG_NDEBUG 0
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080018#define LOG_TAG "libutils.threads"
19
20#include <utils/threads.h>
21#include <utils/Log.h>
22
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -080023#include <cutils/sched_policy.h>
Nick Kralevichc4fd05b2013-02-02 18:09:15 -080024#include <cutils/properties.h>
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -080025
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026#include <stdio.h>
27#include <stdlib.h>
28#include <memory.h>
29#include <errno.h>
30#include <assert.h>
31#include <unistd.h>
32
33#if defined(HAVE_PTHREADS)
34# include <pthread.h>
35# include <sched.h>
36# include <sys/resource.h>
Glenn Kastenba699cb2011-07-11 15:59:22 -070037#ifdef HAVE_ANDROID_OS
38# include <bionic_pthread.h>
39#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040#elif defined(HAVE_WIN32_THREADS)
41# include <windows.h>
42# include <stdint.h>
43# include <process.h>
44# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
45#endif
46
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047#if defined(HAVE_PRCTL)
48#include <sys/prctl.h>
49#endif
50
51/*
52 * ===========================================================================
53 * Thread wrappers
54 * ===========================================================================
55 */
56
57using namespace android;
58
59// ----------------------------------------------------------------------------
60#if defined(HAVE_PTHREADS)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061// ----------------------------------------------------------------------------
62
63/*
Dianne Hackborn7b0d45c2010-09-03 17:07:07 -070064 * Create and run a new thread.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065 *
66 * We create it "detached", so it cleans up after itself.
67 */
68
69typedef void* (*android_pthread_entry)(void*);
70
Dianne Hackborn9c82c482010-09-09 15:50:18 -070071static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
72static bool gDoSchedulingGroup = true;
73
74static void checkDoSchedulingGroup(void) {
75 char buf[PROPERTY_VALUE_MAX];
76 int len = property_get("debug.sys.noschedgroups", buf, "");
77 if (len > 0) {
78 int temp;
79 if (sscanf(buf, "%d", &temp) == 1) {
80 gDoSchedulingGroup = temp == 0;
81 }
82 }
83}
84
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085struct thread_data_t {
86 thread_func_t entryFunction;
87 void* userData;
88 int priority;
89 char * threadName;
90
91 // we use this trampoline when we need to set the priority with
Glenn Kastenba699cb2011-07-11 15:59:22 -070092 // nice/setpriority, and name with prctl.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093 static int trampoline(const thread_data_t* t) {
94 thread_func_t f = t->entryFunction;
95 void* u = t->userData;
96 int prio = t->priority;
97 char * name = t->threadName;
98 delete t;
99 setpriority(PRIO_PROCESS, 0, prio);
Dianne Hackborn9c82c482010-09-09 15:50:18 -0700100 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
101 if (gDoSchedulingGroup) {
102 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
103 set_sched_policy(androidGetTid(), SP_BACKGROUND);
Glenn Kasten10cbbd82012-05-10 15:50:19 -0700104 } else if (prio > ANDROID_PRIORITY_AUDIO) {
Dianne Hackborn9c82c482010-09-09 15:50:18 -0700105 set_sched_policy(androidGetTid(), SP_FOREGROUND);
Glenn Kasten10cbbd82012-05-10 15:50:19 -0700106 } else {
107 // defaults to that of parent, or as set by requestPriority()
Dianne Hackborn9c82c482010-09-09 15:50:18 -0700108 }
109 }
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111 if (name) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800112 androidSetThreadName(name);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800113 free(name);
114 }
115 return f(u);
116 }
117};
118
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800119void androidSetThreadName(const char* name) {
120#if defined(HAVE_PRCTL)
121 // Mac OS doesn't have this, and we build libutil for the host too
122 int hasAt = 0;
123 int hasDot = 0;
124 const char *s = name;
125 while (*s) {
126 if (*s == '.') hasDot = 1;
127 else if (*s == '@') hasAt = 1;
128 s++;
129 }
130 int len = s - name;
131 if (len < 15 || hasAt || !hasDot) {
132 s = name;
133 } else {
134 s = name + len - 15;
135 }
136 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
137#endif
138}
139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
141 void *userData,
142 const char* threadName,
143 int32_t threadPriority,
144 size_t threadStackSize,
145 android_thread_id_t *threadId)
146{
147 pthread_attr_t attr;
148 pthread_attr_init(&attr);
149 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
150
151#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
152 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastenba699cb2011-07-11 15:59:22 -0700153 // Now that the pthread_t has a method to find the associated
154 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
155 // this trampoline in some cases as the parent could set the properties
156 // for the child. However, there would be a race condition because the
157 // child becomes ready immediately, and it doesn't work for the name.
158 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
159 // proposed but not yet accepted.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 thread_data_t* t = new thread_data_t;
161 t->priority = threadPriority;
162 t->threadName = threadName ? strdup(threadName) : NULL;
163 t->entryFunction = entryFunction;
164 t->userData = userData;
165 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
166 userData = t;
167 }
168#endif
169
170 if (threadStackSize) {
171 pthread_attr_setstacksize(&attr, threadStackSize);
172 }
173
174 errno = 0;
175 pthread_t thread;
176 int result = pthread_create(&thread, &attr,
177 (android_pthread_entry)entryFunction, userData);
Le-Chun Wu39199502011-07-14 14:27:18 -0700178 pthread_attr_destroy(&attr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 if (result != 0) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000180 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 "(android threadPriority=%d)",
182 entryFunction, result, errno, threadPriority);
183 return 0;
184 }
185
Glenn Kastend9e1bb72011-06-02 08:59:28 -0700186 // Note that *threadID is directly available to the parent only, as it is
187 // assigned after the child starts. Use memory barrier / lock if the child
188 // or other threads also need access.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189 if (threadId != NULL) {
190 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
191 }
192 return 1;
193}
194
Glenn Kastenba699cb2011-07-11 15:59:22 -0700195#ifdef HAVE_ANDROID_OS
196static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
197{
198 return (pthread_t) thread;
199}
200#endif
201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202android_thread_id_t androidGetThreadId()
203{
204 return (android_thread_id_t)pthread_self();
205}
206
207// ----------------------------------------------------------------------------
208#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209// ----------------------------------------------------------------------------
210
211/*
212 * Trampoline to make us __stdcall-compliant.
213 *
214 * We're expected to delete "vDetails" when we're done.
215 */
216struct threadDetails {
217 int (*func)(void*);
218 void* arg;
219};
220static __stdcall unsigned int threadIntermediary(void* vDetails)
221{
222 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
223 int result;
224
225 result = (*(pDetails->func))(pDetails->arg);
226
227 delete pDetails;
228
Steve Block9f760152011-10-12 17:27:03 +0100229 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 return (unsigned int) result;
231}
232
233/*
234 * Create and run a new thread.
235 */
236static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
237{
238 HANDLE hThread;
239 struct threadDetails* pDetails = new threadDetails; // must be on heap
240 unsigned int thrdaddr;
241
242 pDetails->func = fn;
243 pDetails->arg = arg;
244
245#if defined(HAVE__BEGINTHREADEX)
246 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
247 &thrdaddr);
248 if (hThread == 0)
249#elif defined(HAVE_CREATETHREAD)
250 hThread = CreateThread(NULL, 0,
251 (LPTHREAD_START_ROUTINE) threadIntermediary,
252 (void*) pDetails, 0, (DWORD*) &thrdaddr);
253 if (hThread == NULL)
254#endif
255 {
Steve Block9f760152011-10-12 17:27:03 +0100256 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 return false;
258 }
259
260#if defined(HAVE_CREATETHREAD)
261 /* close the management handle */
262 CloseHandle(hThread);
263#endif
264
265 if (id != NULL) {
266 *id = (android_thread_id_t)thrdaddr;
267 }
268
269 return true;
270}
271
272int androidCreateRawThreadEtc(android_thread_func_t fn,
273 void *userData,
274 const char* threadName,
275 int32_t threadPriority,
276 size_t threadStackSize,
277 android_thread_id_t *threadId)
278{
279 return doCreateThread( fn, userData, threadId);
280}
281
282android_thread_id_t androidGetThreadId()
283{
284 return (android_thread_id_t)GetCurrentThreadId();
285}
286
287// ----------------------------------------------------------------------------
288#else
289#error "Threads not supported"
290#endif
291
292// ----------------------------------------------------------------------------
293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294int androidCreateThread(android_thread_func_t fn, void* arg)
295{
296 return createThreadEtc(fn, arg);
297}
298
299int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
300{
301 return createThreadEtc(fn, arg, "android:unnamed_thread",
302 PRIORITY_DEFAULT, 0, id);
303}
304
305static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
306
307int androidCreateThreadEtc(android_thread_func_t entryFunction,
308 void *userData,
309 const char* threadName,
310 int32_t threadPriority,
311 size_t threadStackSize,
312 android_thread_id_t *threadId)
313{
314 return gCreateThreadFn(entryFunction, userData, threadName,
315 threadPriority, threadStackSize, threadId);
316}
317
318void androidSetCreateThreadFunc(android_create_thread_fn func)
319{
320 gCreateThreadFn = func;
321}
322
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800323pid_t androidGetTid()
324{
325#ifdef HAVE_GETTID
326 return gettid();
327#else
328 return getpid();
329#endif
330}
331
Jeff Brown0818b092012-03-16 22:18:39 -0700332#ifdef HAVE_ANDROID_OS
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800333int androidSetThreadPriority(pid_t tid, int pri)
334{
335 int rc = 0;
Dianne Hackbornd0aecce2009-12-08 19:45:59 -0800336
337#if defined(HAVE_PTHREADS)
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800338 int lasterr = 0;
339
Dianne Hackborn7b0d45c2010-09-03 17:07:07 -0700340 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
341 if (gDoSchedulingGroup) {
Glenn Kastenf0c41252011-06-14 10:35:34 -0700342 // set_sched_policy does not support tid == 0
343 int policy_tid;
344 if (tid == 0) {
345 policy_tid = androidGetTid();
346 } else {
347 policy_tid = tid;
348 }
Dianne Hackborn7b0d45c2010-09-03 17:07:07 -0700349 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kastenf0c41252011-06-14 10:35:34 -0700350 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn7b0d45c2010-09-03 17:07:07 -0700351 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kastenf0c41252011-06-14 10:35:34 -0700352 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn7b0d45c2010-09-03 17:07:07 -0700353 }
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800354 }
355
356 if (rc) {
357 lasterr = errno;
358 }
359
360 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
361 rc = INVALID_OPERATION;
362 } else {
363 errno = lasterr;
364 }
Dianne Hackbornc5b13892009-12-08 16:38:01 -0800365#endif
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800366
367 return rc;
368}
369
Andreas Huber1d60b962011-09-15 12:21:40 -0700370int androidGetThreadPriority(pid_t tid) {
Andreas Huber9dbb77d2011-09-16 11:47:13 -0700371#if defined(HAVE_PTHREADS)
Andreas Huber1d60b962011-09-15 12:21:40 -0700372 return getpriority(PRIO_PROCESS, tid);
Andreas Huber9dbb77d2011-09-16 11:47:13 -0700373#else
374 return ANDROID_PRIORITY_NORMAL;
375#endif
Andreas Huber1d60b962011-09-15 12:21:40 -0700376}
377
Jeff Brown0818b092012-03-16 22:18:39 -0700378#endif
Glenn Kasten4fb24272011-06-22 16:20:37 -0700379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380namespace android {
381
382/*
383 * ===========================================================================
384 * Mutex class
385 * ===========================================================================
386 */
387
Mathias Agopianec0f1f62009-07-12 23:11:20 -0700388#if defined(HAVE_PTHREADS)
389// implemented as inlines in threads.h
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391
392Mutex::Mutex()
393{
394 HANDLE hMutex;
395
396 assert(sizeof(hMutex) == sizeof(mState));
397
398 hMutex = CreateMutex(NULL, FALSE, NULL);
399 mState = (void*) hMutex;
400}
401
402Mutex::Mutex(const char* name)
403{
404 // XXX: name not used for now
405 HANDLE hMutex;
406
David 'Digit' Turner429db152009-08-01 00:20:17 +0200407 assert(sizeof(hMutex) == sizeof(mState));
408
409 hMutex = CreateMutex(NULL, FALSE, NULL);
410 mState = (void*) hMutex;
411}
412
413Mutex::Mutex(int type, const char* name)
414{
415 // XXX: type and name not used for now
416 HANDLE hMutex;
417
418 assert(sizeof(hMutex) == sizeof(mState));
419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420 hMutex = CreateMutex(NULL, FALSE, NULL);
421 mState = (void*) hMutex;
422}
423
424Mutex::~Mutex()
425{
426 CloseHandle((HANDLE) mState);
427}
428
429status_t Mutex::lock()
430{
431 DWORD dwWaitResult;
432 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
433 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
434}
435
436void Mutex::unlock()
437{
438 if (!ReleaseMutex((HANDLE) mState))
Steve Block9f760152011-10-12 17:27:03 +0100439 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440}
441
442status_t Mutex::tryLock()
443{
444 DWORD dwWaitResult;
445
446 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
447 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block9f760152011-10-12 17:27:03 +0100448 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
450}
451
452#else
453#error "Somebody forgot to implement threads for this platform."
454#endif
455
456
457/*
458 * ===========================================================================
459 * Condition class
460 * ===========================================================================
461 */
462
Mathias Agopianec0f1f62009-07-12 23:11:20 -0700463#if defined(HAVE_PTHREADS)
464// implemented as inlines in threads.h
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800466
467/*
468 * Windows doesn't have a condition variable solution. It's possible
469 * to create one, but it's easy to get it wrong. For a discussion, and
470 * the origin of this implementation, see:
471 *
472 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
473 *
474 * The implementation shown on the page does NOT follow POSIX semantics.
475 * As an optimization they require acquiring the external mutex before
476 * calling signal() and broadcast(), whereas POSIX only requires grabbing
477 * it before calling wait(). The implementation here has been un-optimized
478 * to have the correct behavior.
479 */
480typedef struct WinCondition {
481 // Number of waiting threads.
482 int waitersCount;
483
484 // Serialize access to waitersCount.
485 CRITICAL_SECTION waitersCountLock;
486
487 // Semaphore used to queue up threads waiting for the condition to
488 // become signaled.
489 HANDLE sema;
490
491 // An auto-reset event used by the broadcast/signal thread to wait
492 // for all the waiting thread(s) to wake up and be released from
493 // the semaphore.
494 HANDLE waitersDone;
495
496 // This mutex wouldn't be necessary if we required that the caller
497 // lock the external mutex before calling signal() and broadcast().
498 // I'm trying to mimic pthread semantics though.
499 HANDLE internalMutex;
500
501 // Keeps track of whether we were broadcasting or signaling. This
502 // allows us to optimize the code if we're just signaling.
503 bool wasBroadcast;
504
505 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
506 {
507 // Increment the wait count, avoiding race conditions.
508 EnterCriticalSection(&condState->waitersCountLock);
509 condState->waitersCount++;
510 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
511 // condState->waitersCount, getThreadId());
512 LeaveCriticalSection(&condState->waitersCountLock);
513
514 DWORD timeout = INFINITE;
515 if (abstime) {
516 nsecs_t reltime = *abstime - systemTime();
517 if (reltime < 0)
518 reltime = 0;
519 timeout = reltime/1000000;
520 }
521
522 // Atomically release the external mutex and wait on the semaphore.
523 DWORD res =
524 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
525
526 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
527
528 // Reacquire lock to avoid race conditions.
529 EnterCriticalSection(&condState->waitersCountLock);
530
531 // No longer waiting.
532 condState->waitersCount--;
533
534 // Check to see if we're the last waiter after a broadcast.
535 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
536
537 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
538 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
539
540 LeaveCriticalSection(&condState->waitersCountLock);
541
542 // If we're the last waiter thread during this particular broadcast
543 // then signal broadcast() that we're all awake. It'll drop the
544 // internal mutex.
545 if (lastWaiter) {
546 // Atomically signal the "waitersDone" event and wait until we
547 // can acquire the internal mutex. We want to do this in one step
548 // because it ensures that everybody is in the mutex FIFO before
549 // any thread has a chance to run. Without it, another thread
550 // could wake up, do work, and hop back in ahead of us.
551 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
552 INFINITE, FALSE);
553 } else {
554 // Grab the internal mutex.
555 WaitForSingleObject(condState->internalMutex, INFINITE);
556 }
557
558 // Release the internal and grab the external.
559 ReleaseMutex(condState->internalMutex);
560 WaitForSingleObject(hMutex, INFINITE);
561
562 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
563 }
564} WinCondition;
565
566/*
567 * Constructor. Set up the WinCondition stuff.
568 */
569Condition::Condition()
570{
571 WinCondition* condState = new WinCondition;
572
573 condState->waitersCount = 0;
574 condState->wasBroadcast = false;
575 // semaphore: no security, initial value of 0
576 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
577 InitializeCriticalSection(&condState->waitersCountLock);
578 // auto-reset event, not signaled initially
579 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
580 // used so we don't have to lock external mutex on signal/broadcast
581 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
582
583 mState = condState;
584}
585
586/*
587 * Destructor. Free Windows resources as well as our allocated storage.
588 */
589Condition::~Condition()
590{
591 WinCondition* condState = (WinCondition*) mState;
592 if (condState != NULL) {
593 CloseHandle(condState->sema);
594 CloseHandle(condState->waitersDone);
595 delete condState;
596 }
597}
598
599
600status_t Condition::wait(Mutex& mutex)
601{
602 WinCondition* condState = (WinCondition*) mState;
603 HANDLE hMutex = (HANDLE) mutex.mState;
604
605 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
606}
607
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800608status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
609{
David 'Digit' Turner429db152009-08-01 00:20:17 +0200610 WinCondition* condState = (WinCondition*) mState;
611 HANDLE hMutex = (HANDLE) mutex.mState;
612 nsecs_t absTime = systemTime()+reltime;
613
614 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800615}
616
617/*
618 * Signal the condition variable, allowing one thread to continue.
619 */
620void Condition::signal()
621{
622 WinCondition* condState = (WinCondition*) mState;
623
624 // Lock the internal mutex. This ensures that we don't clash with
625 // broadcast().
626 WaitForSingleObject(condState->internalMutex, INFINITE);
627
628 EnterCriticalSection(&condState->waitersCountLock);
629 bool haveWaiters = (condState->waitersCount > 0);
630 LeaveCriticalSection(&condState->waitersCountLock);
631
632 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
633 // down a notch.
634 if (haveWaiters)
635 ReleaseSemaphore(condState->sema, 1, 0);
636
637 // Release internal mutex.
638 ReleaseMutex(condState->internalMutex);
639}
640
641/*
642 * Signal the condition variable, allowing all threads to continue.
643 *
644 * First we have to wake up all threads waiting on the semaphore, then
645 * we wait until all of the threads have actually been woken before
646 * releasing the internal mutex. This ensures that all threads are woken.
647 */
648void Condition::broadcast()
649{
650 WinCondition* condState = (WinCondition*) mState;
651
652 // Lock the internal mutex. This keeps the guys we're waking up
653 // from getting too far.
654 WaitForSingleObject(condState->internalMutex, INFINITE);
655
656 EnterCriticalSection(&condState->waitersCountLock);
657 bool haveWaiters = false;
658
659 if (condState->waitersCount > 0) {
660 haveWaiters = true;
661 condState->wasBroadcast = true;
662 }
663
664 if (haveWaiters) {
665 // Wake up all the waiters.
666 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
667
668 LeaveCriticalSection(&condState->waitersCountLock);
669
670 // Wait for all awakened threads to acquire the counting semaphore.
671 // The last guy who was waiting sets this.
672 WaitForSingleObject(condState->waitersDone, INFINITE);
673
674 // Reset wasBroadcast. (No crit section needed because nobody
675 // else can wake up to poke at it.)
676 condState->wasBroadcast = 0;
677 } else {
678 // nothing to do
679 LeaveCriticalSection(&condState->waitersCountLock);
680 }
681
682 // Release internal mutex.
683 ReleaseMutex(condState->internalMutex);
684}
685
686#else
687#error "condition variables not supported on this platform"
688#endif
689
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800690// ----------------------------------------------------------------------------
691
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692/*
693 * This is our thread object!
694 */
695
696Thread::Thread(bool canCallJava)
697 : mCanCallJava(canCallJava),
698 mThread(thread_id_t(-1)),
699 mLock("Thread::mLock"),
700 mStatus(NO_ERROR),
701 mExitPending(false), mRunning(false)
Glenn Kasten7e453a52011-02-01 11:32:29 -0800702#ifdef HAVE_ANDROID_OS
703 , mTid(-1)
704#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705{
706}
707
708Thread::~Thread()
709{
710}
711
712status_t Thread::readyToRun()
713{
714 return NO_ERROR;
715}
716
717status_t Thread::run(const char* name, int32_t priority, size_t stack)
718{
719 Mutex::Autolock _l(mLock);
720
721 if (mRunning) {
722 // thread already started
723 return INVALID_OPERATION;
724 }
725
726 // reset status and exitPending to their default value, so we can
727 // try again after an error happened (either below, or in readyToRun())
728 mStatus = NO_ERROR;
729 mExitPending = false;
730 mThread = thread_id_t(-1);
731
732 // hold a strong reference on ourself
733 mHoldSelf = this;
734
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800735 mRunning = true;
736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800737 bool res;
738 if (mCanCallJava) {
739 res = createThreadEtc(_threadLoop,
740 this, name, priority, stack, &mThread);
741 } else {
742 res = androidCreateRawThreadEtc(_threadLoop,
743 this, name, priority, stack, &mThread);
744 }
745
746 if (res == false) {
747 mStatus = UNKNOWN_ERROR; // something happened!
748 mRunning = false;
749 mThread = thread_id_t(-1);
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800750 mHoldSelf.clear(); // "this" may have gone away after this.
751
752 return UNKNOWN_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800753 }
754
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800755 // Do not refer to mStatus here: The thread is already running (may, in fact
756 // already have exited with a valid mStatus result). The NO_ERROR indication
757 // here merely indicates successfully starting the thread and does not
758 // imply successful termination/execution.
759 return NO_ERROR;
Glenn Kasten7e453a52011-02-01 11:32:29 -0800760
761 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800762}
763
764int Thread::_threadLoop(void* user)
765{
766 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten7e453a52011-02-01 11:32:29 -0800767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800768 sp<Thread> strong(self->mHoldSelf);
769 wp<Thread> weak(strong);
770 self->mHoldSelf.clear();
771
Kenny Rootaf1cf072011-02-16 10:13:53 -0800772#ifdef HAVE_ANDROID_OS
Mathias Agopian4de4ebf2009-09-09 02:38:13 -0700773 // this is very useful for debugging with gdb
774 self->mTid = gettid();
775#endif
776
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800777 bool first = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778
779 do {
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800780 bool result;
781 if (first) {
782 first = false;
783 self->mStatus = self->readyToRun();
784 result = (self->mStatus == NO_ERROR);
785
Glenn Kasten7e453a52011-02-01 11:32:29 -0800786 if (result && !self->exitPending()) {
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800787 // Binder threads (and maybe others) rely on threadLoop
788 // running at least once after a successful ::readyToRun()
789 // (unless, of course, the thread has already been asked to exit
790 // at that point).
791 // This is because threads are essentially used like this:
792 // (new ThreadSubclass())->run();
793 // The caller therefore does not retain a strong reference to
794 // the thread and the thread would simply disappear after the
795 // successful ::readyToRun() call instead of entering the
796 // threadLoop at least once.
797 result = self->threadLoop();
798 }
799 } else {
800 result = self->threadLoop();
801 }
802
Glenn Kasten7e453a52011-02-01 11:32:29 -0800803 // establish a scope for mLock
804 {
805 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800806 if (result == false || self->mExitPending) {
807 self->mExitPending = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800808 self->mRunning = false;
Eric Laurenta017d5b2011-01-04 11:58:04 -0800809 // clear thread ID so that requestExitAndWait() does not exit if
810 // called by a new thread using the same thread ID as this one.
811 self->mThread = thread_id_t(-1);
Glenn Kasten7e453a52011-02-01 11:32:29 -0800812 // note that interested observers blocked in requestExitAndWait are
813 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian4de4ebf2009-09-09 02:38:13 -0700814 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800815 break;
816 }
Glenn Kasten7e453a52011-02-01 11:32:29 -0800817 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800818
819 // Release our strong reference, to let a chance to the thread
820 // to die a peaceful death.
821 strong.clear();
Mathias Agopian4de4ebf2009-09-09 02:38:13 -0700822 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800823 strong = weak.promote();
824 } while(strong != 0);
825
826 return 0;
827}
828
829void Thread::requestExit()
830{
Glenn Kasten7e453a52011-02-01 11:32:29 -0800831 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800832 mExitPending = true;
833}
834
835status_t Thread::requestExitAndWait()
836{
Glenn Kastend9e1bb72011-06-02 08:59:28 -0700837 Mutex::Autolock _l(mLock);
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800838 if (mThread == getThreadId()) {
Steve Block32397c12012-01-05 23:22:43 +0000839 ALOGW(
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800840 "Thread (this=%p): don't call waitForExit() from this "
841 "Thread object's thread. It's a guaranteed deadlock!",
842 this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800843
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800844 return WOULD_BLOCK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800845 }
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800846
Glenn Kastend9e1bb72011-06-02 08:59:28 -0700847 mExitPending = true;
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800848
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800849 while (mRunning == true) {
850 mThreadExitedCondition.wait(mLock);
851 }
Glenn Kasten7e453a52011-02-01 11:32:29 -0800852 // This next line is probably not needed any more, but is being left for
853 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project9adf84a2009-03-05 14:34:35 -0800854 mExitPending = false;
855
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800856 return mStatus;
857}
858
Glenn Kasten58e012d2011-06-23 12:55:29 -0700859status_t Thread::join()
860{
861 Mutex::Autolock _l(mLock);
862 if (mThread == getThreadId()) {
Steve Block32397c12012-01-05 23:22:43 +0000863 ALOGW(
Glenn Kasten58e012d2011-06-23 12:55:29 -0700864 "Thread (this=%p): don't call join() from this "
865 "Thread object's thread. It's a guaranteed deadlock!",
866 this);
867
868 return WOULD_BLOCK;
869 }
870
871 while (mRunning == true) {
872 mThreadExitedCondition.wait(mLock);
873 }
874
875 return mStatus;
876}
877
Glenn Kastenba699cb2011-07-11 15:59:22 -0700878#ifdef HAVE_ANDROID_OS
879pid_t Thread::getTid() const
880{
881 // mTid is not defined until the child initializes it, and the caller may need it earlier
882 Mutex::Autolock _l(mLock);
883 pid_t tid;
884 if (mRunning) {
885 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
886 tid = __pthread_gettid(pthread);
887 } else {
888 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
889 tid = -1;
890 }
891 return tid;
892}
893#endif
894
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800895bool Thread::exitPending() const
896{
Glenn Kasten7e453a52011-02-01 11:32:29 -0800897 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800898 return mExitPending;
899}
900
901
902
903}; // namespace android