blob: d18c0a2f5a742098a428a69fb6b360ea7d128646 [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Project4df24232009-03-05 14:34:35 -080017// #define LOG_NDEBUG 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018#define LOG_TAG "libutils.threads"
19
20#include <utils/threads.h>
21#include <utils/Log.h>
22
Dianne Hackborn887f3552009-12-07 17:59:37 -080023#include <cutils/sched_policy.h>
Dianne Hackborn84bb52e2010-09-03 17:07:07 -070024#include <cutils/properties.h>
Dianne Hackborn887f3552009-12-07 17:59:37 -080025
The Android Open Source Project9066cfe2009-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>
37#elif defined(HAVE_WIN32_THREADS)
38# include <windows.h>
39# include <stdint.h>
40# include <process.h>
41# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
42#endif
43
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044#if defined(HAVE_PRCTL)
45#include <sys/prctl.h>
46#endif
47
48/*
49 * ===========================================================================
50 * Thread wrappers
51 * ===========================================================================
52 */
53
54using namespace android;
55
56// ----------------------------------------------------------------------------
57#if defined(HAVE_PTHREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058// ----------------------------------------------------------------------------
59
60/*
Dianne Hackborn84bb52e2010-09-03 17:07:07 -070061 * Create and run a new thread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 *
63 * We create it "detached", so it cleans up after itself.
64 */
65
66typedef void* (*android_pthread_entry)(void*);
67
Dianne Hackborna8512a72010-09-09 15:50:18 -070068static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
69static bool gDoSchedulingGroup = true;
70
71static void checkDoSchedulingGroup(void) {
72 char buf[PROPERTY_VALUE_MAX];
73 int len = property_get("debug.sys.noschedgroups", buf, "");
74 if (len > 0) {
75 int temp;
76 if (sscanf(buf, "%d", &temp) == 1) {
77 gDoSchedulingGroup = temp == 0;
78 }
79 }
80}
81
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082struct thread_data_t {
83 thread_func_t entryFunction;
84 void* userData;
85 int priority;
86 char * threadName;
87
88 // we use this trampoline when we need to set the priority with
89 // nice/setpriority.
90 static int trampoline(const thread_data_t* t) {
91 thread_func_t f = t->entryFunction;
92 void* u = t->userData;
93 int prio = t->priority;
94 char * name = t->threadName;
95 delete t;
96 setpriority(PRIO_PROCESS, 0, prio);
Dianne Hackborna8512a72010-09-09 15:50:18 -070097 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
98 if (gDoSchedulingGroup) {
99 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
100 set_sched_policy(androidGetTid(), SP_BACKGROUND);
101 } else {
102 set_sched_policy(androidGetTid(), SP_FOREGROUND);
103 }
104 }
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 if (name) {
107#if defined(HAVE_PRCTL)
108 // Mac OS doesn't have this, and we build libutil for the host too
109 int hasAt = 0;
110 int hasDot = 0;
111 char *s = name;
112 while (*s) {
113 if (*s == '.') hasDot = 1;
114 else if (*s == '@') hasAt = 1;
115 s++;
116 }
117 int len = s - name;
118 if (len < 15 || hasAt || !hasDot) {
119 s = name;
120 } else {
121 s = name + len - 15;
122 }
123 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
124#endif
125 free(name);
126 }
127 return f(u);
128 }
129};
130
131int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
132 void *userData,
133 const char* threadName,
134 int32_t threadPriority,
135 size_t threadStackSize,
136 android_thread_id_t *threadId)
137{
138 pthread_attr_t attr;
139 pthread_attr_init(&attr);
140 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
141
142#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
143 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
144 // We could avoid the trampoline if there was a way to get to the
145 // android_thread_id_t (pid) from pthread_t
146 thread_data_t* t = new thread_data_t;
147 t->priority = threadPriority;
148 t->threadName = threadName ? strdup(threadName) : NULL;
149 t->entryFunction = entryFunction;
150 t->userData = userData;
151 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
152 userData = t;
153 }
154#endif
155
156 if (threadStackSize) {
157 pthread_attr_setstacksize(&attr, threadStackSize);
158 }
159
160 errno = 0;
161 pthread_t thread;
162 int result = pthread_create(&thread, &attr,
163 (android_pthread_entry)entryFunction, userData);
Le-Chun Wuda135602011-07-14 14:27:18 -0700164 pthread_attr_destroy(&attr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 if (result != 0) {
166 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
167 "(android threadPriority=%d)",
168 entryFunction, result, errno, threadPriority);
169 return 0;
170 }
171
Glenn Kasten9dbd7d82011-06-02 08:59:28 -0700172 // Note that *threadID is directly available to the parent only, as it is
173 // assigned after the child starts. Use memory barrier / lock if the child
174 // or other threads also need access.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 if (threadId != NULL) {
176 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
177 }
178 return 1;
179}
180
181android_thread_id_t androidGetThreadId()
182{
183 return (android_thread_id_t)pthread_self();
184}
185
186// ----------------------------------------------------------------------------
187#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188// ----------------------------------------------------------------------------
189
190/*
191 * Trampoline to make us __stdcall-compliant.
192 *
193 * We're expected to delete "vDetails" when we're done.
194 */
195struct threadDetails {
196 int (*func)(void*);
197 void* arg;
198};
199static __stdcall unsigned int threadIntermediary(void* vDetails)
200{
201 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
202 int result;
203
204 result = (*(pDetails->func))(pDetails->arg);
205
206 delete pDetails;
207
208 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
209 return (unsigned int) result;
210}
211
212/*
213 * Create and run a new thread.
214 */
215static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
216{
217 HANDLE hThread;
218 struct threadDetails* pDetails = new threadDetails; // must be on heap
219 unsigned int thrdaddr;
220
221 pDetails->func = fn;
222 pDetails->arg = arg;
223
224#if defined(HAVE__BEGINTHREADEX)
225 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
226 &thrdaddr);
227 if (hThread == 0)
228#elif defined(HAVE_CREATETHREAD)
229 hThread = CreateThread(NULL, 0,
230 (LPTHREAD_START_ROUTINE) threadIntermediary,
231 (void*) pDetails, 0, (DWORD*) &thrdaddr);
232 if (hThread == NULL)
233#endif
234 {
235 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
236 return false;
237 }
238
239#if defined(HAVE_CREATETHREAD)
240 /* close the management handle */
241 CloseHandle(hThread);
242#endif
243
244 if (id != NULL) {
245 *id = (android_thread_id_t)thrdaddr;
246 }
247
248 return true;
249}
250
251int androidCreateRawThreadEtc(android_thread_func_t fn,
252 void *userData,
253 const char* threadName,
254 int32_t threadPriority,
255 size_t threadStackSize,
256 android_thread_id_t *threadId)
257{
258 return doCreateThread( fn, userData, threadId);
259}
260
261android_thread_id_t androidGetThreadId()
262{
263 return (android_thread_id_t)GetCurrentThreadId();
264}
265
266// ----------------------------------------------------------------------------
267#else
268#error "Threads not supported"
269#endif
270
271// ----------------------------------------------------------------------------
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273int androidCreateThread(android_thread_func_t fn, void* arg)
274{
275 return createThreadEtc(fn, arg);
276}
277
278int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
279{
280 return createThreadEtc(fn, arg, "android:unnamed_thread",
281 PRIORITY_DEFAULT, 0, id);
282}
283
284static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
285
286int androidCreateThreadEtc(android_thread_func_t entryFunction,
287 void *userData,
288 const char* threadName,
289 int32_t threadPriority,
290 size_t threadStackSize,
291 android_thread_id_t *threadId)
292{
293 return gCreateThreadFn(entryFunction, userData, threadName,
294 threadPriority, threadStackSize, threadId);
295}
296
297void androidSetCreateThreadFunc(android_create_thread_fn func)
298{
299 gCreateThreadFn = func;
300}
301
Dianne Hackborn887f3552009-12-07 17:59:37 -0800302pid_t androidGetTid()
303{
304#ifdef HAVE_GETTID
305 return gettid();
306#else
307 return getpid();
308#endif
309}
310
311int androidSetThreadSchedulingGroup(pid_t tid, int grp)
312{
313 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
314 return BAD_VALUE;
315 }
316
Dianne Hackbornafbeb312009-12-08 19:45:59 -0800317#if defined(HAVE_PTHREADS)
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700318 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
319 if (gDoSchedulingGroup) {
Glenn Kasten60d47792011-06-22 17:42:23 -0700320 // set_sched_policy does not support tid == 0
321 if (tid == 0) {
322 tid = androidGetTid();
323 }
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700324 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
325 SP_BACKGROUND : SP_FOREGROUND)) {
326 return PERMISSION_DENIED;
327 }
Dianne Hackborn887f3552009-12-07 17:59:37 -0800328 }
Dianne Hackbornafbeb312009-12-08 19:45:59 -0800329#endif
Dianne Hackborn887f3552009-12-07 17:59:37 -0800330
331 return NO_ERROR;
332}
333
334int androidSetThreadPriority(pid_t tid, int pri)
335{
336 int rc = 0;
Dianne Hackbornafbeb312009-12-08 19:45:59 -0800337
338#if defined(HAVE_PTHREADS)
Dianne Hackborn887f3552009-12-07 17:59:37 -0800339 int lasterr = 0;
340
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700341 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
342 if (gDoSchedulingGroup) {
Glenn Kasten1d24aaa2011-06-14 10:35:34 -0700343 // set_sched_policy does not support tid == 0
344 int policy_tid;
345 if (tid == 0) {
346 policy_tid = androidGetTid();
347 } else {
348 policy_tid = tid;
349 }
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700350 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten1d24aaa2011-06-14 10:35:34 -0700351 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700352 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten1d24aaa2011-06-14 10:35:34 -0700353 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700354 }
Dianne Hackborn887f3552009-12-07 17:59:37 -0800355 }
356
357 if (rc) {
358 lasterr = errno;
359 }
360
361 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
362 rc = INVALID_OPERATION;
363 } else {
364 errno = lasterr;
365 }
Dianne Hackborn06fb2c12009-12-08 16:38:01 -0800366#endif
Dianne Hackborn887f3552009-12-07 17:59:37 -0800367
368 return rc;
369}
370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371namespace android {
372
373/*
374 * ===========================================================================
375 * Mutex class
376 * ===========================================================================
377 */
378
Mathias Agopianb1c4ca52009-07-12 23:11:20 -0700379#if defined(HAVE_PTHREADS)
380// implemented as inlines in threads.h
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382
383Mutex::Mutex()
384{
385 HANDLE hMutex;
386
387 assert(sizeof(hMutex) == sizeof(mState));
388
389 hMutex = CreateMutex(NULL, FALSE, NULL);
390 mState = (void*) hMutex;
391}
392
393Mutex::Mutex(const char* name)
394{
395 // XXX: name not used for now
396 HANDLE hMutex;
397
David 'Digit' Turner078a2752009-08-01 00:20:17 +0200398 assert(sizeof(hMutex) == sizeof(mState));
399
400 hMutex = CreateMutex(NULL, FALSE, NULL);
401 mState = (void*) hMutex;
402}
403
404Mutex::Mutex(int type, const char* name)
405{
406 // XXX: type and name not used for now
407 HANDLE hMutex;
408
409 assert(sizeof(hMutex) == sizeof(mState));
410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 hMutex = CreateMutex(NULL, FALSE, NULL);
412 mState = (void*) hMutex;
413}
414
415Mutex::~Mutex()
416{
417 CloseHandle((HANDLE) mState);
418}
419
420status_t Mutex::lock()
421{
422 DWORD dwWaitResult;
423 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
424 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
425}
426
427void Mutex::unlock()
428{
429 if (!ReleaseMutex((HANDLE) mState))
430 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
431}
432
433status_t Mutex::tryLock()
434{
435 DWORD dwWaitResult;
436
437 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
438 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
439 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
440 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
441}
442
443#else
444#error "Somebody forgot to implement threads for this platform."
445#endif
446
447
448/*
449 * ===========================================================================
450 * Condition class
451 * ===========================================================================
452 */
453
Mathias Agopianb1c4ca52009-07-12 23:11:20 -0700454#if defined(HAVE_PTHREADS)
455// implemented as inlines in threads.h
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457
458/*
459 * Windows doesn't have a condition variable solution. It's possible
460 * to create one, but it's easy to get it wrong. For a discussion, and
461 * the origin of this implementation, see:
462 *
463 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
464 *
465 * The implementation shown on the page does NOT follow POSIX semantics.
466 * As an optimization they require acquiring the external mutex before
467 * calling signal() and broadcast(), whereas POSIX only requires grabbing
468 * it before calling wait(). The implementation here has been un-optimized
469 * to have the correct behavior.
470 */
471typedef struct WinCondition {
472 // Number of waiting threads.
473 int waitersCount;
474
475 // Serialize access to waitersCount.
476 CRITICAL_SECTION waitersCountLock;
477
478 // Semaphore used to queue up threads waiting for the condition to
479 // become signaled.
480 HANDLE sema;
481
482 // An auto-reset event used by the broadcast/signal thread to wait
483 // for all the waiting thread(s) to wake up and be released from
484 // the semaphore.
485 HANDLE waitersDone;
486
487 // This mutex wouldn't be necessary if we required that the caller
488 // lock the external mutex before calling signal() and broadcast().
489 // I'm trying to mimic pthread semantics though.
490 HANDLE internalMutex;
491
492 // Keeps track of whether we were broadcasting or signaling. This
493 // allows us to optimize the code if we're just signaling.
494 bool wasBroadcast;
495
496 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
497 {
498 // Increment the wait count, avoiding race conditions.
499 EnterCriticalSection(&condState->waitersCountLock);
500 condState->waitersCount++;
501 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
502 // condState->waitersCount, getThreadId());
503 LeaveCriticalSection(&condState->waitersCountLock);
504
505 DWORD timeout = INFINITE;
506 if (abstime) {
507 nsecs_t reltime = *abstime - systemTime();
508 if (reltime < 0)
509 reltime = 0;
510 timeout = reltime/1000000;
511 }
512
513 // Atomically release the external mutex and wait on the semaphore.
514 DWORD res =
515 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
516
517 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
518
519 // Reacquire lock to avoid race conditions.
520 EnterCriticalSection(&condState->waitersCountLock);
521
522 // No longer waiting.
523 condState->waitersCount--;
524
525 // Check to see if we're the last waiter after a broadcast.
526 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
527
528 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
529 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
530
531 LeaveCriticalSection(&condState->waitersCountLock);
532
533 // If we're the last waiter thread during this particular broadcast
534 // then signal broadcast() that we're all awake. It'll drop the
535 // internal mutex.
536 if (lastWaiter) {
537 // Atomically signal the "waitersDone" event and wait until we
538 // can acquire the internal mutex. We want to do this in one step
539 // because it ensures that everybody is in the mutex FIFO before
540 // any thread has a chance to run. Without it, another thread
541 // could wake up, do work, and hop back in ahead of us.
542 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
543 INFINITE, FALSE);
544 } else {
545 // Grab the internal mutex.
546 WaitForSingleObject(condState->internalMutex, INFINITE);
547 }
548
549 // Release the internal and grab the external.
550 ReleaseMutex(condState->internalMutex);
551 WaitForSingleObject(hMutex, INFINITE);
552
553 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
554 }
555} WinCondition;
556
557/*
558 * Constructor. Set up the WinCondition stuff.
559 */
560Condition::Condition()
561{
562 WinCondition* condState = new WinCondition;
563
564 condState->waitersCount = 0;
565 condState->wasBroadcast = false;
566 // semaphore: no security, initial value of 0
567 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
568 InitializeCriticalSection(&condState->waitersCountLock);
569 // auto-reset event, not signaled initially
570 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
571 // used so we don't have to lock external mutex on signal/broadcast
572 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
573
574 mState = condState;
575}
576
577/*
578 * Destructor. Free Windows resources as well as our allocated storage.
579 */
580Condition::~Condition()
581{
582 WinCondition* condState = (WinCondition*) mState;
583 if (condState != NULL) {
584 CloseHandle(condState->sema);
585 CloseHandle(condState->waitersDone);
586 delete condState;
587 }
588}
589
590
591status_t Condition::wait(Mutex& mutex)
592{
593 WinCondition* condState = (WinCondition*) mState;
594 HANDLE hMutex = (HANDLE) mutex.mState;
595
596 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
597}
598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
600{
David 'Digit' Turner078a2752009-08-01 00:20:17 +0200601 WinCondition* condState = (WinCondition*) mState;
602 HANDLE hMutex = (HANDLE) mutex.mState;
603 nsecs_t absTime = systemTime()+reltime;
604
605 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606}
607
608/*
609 * Signal the condition variable, allowing one thread to continue.
610 */
611void Condition::signal()
612{
613 WinCondition* condState = (WinCondition*) mState;
614
615 // Lock the internal mutex. This ensures that we don't clash with
616 // broadcast().
617 WaitForSingleObject(condState->internalMutex, INFINITE);
618
619 EnterCriticalSection(&condState->waitersCountLock);
620 bool haveWaiters = (condState->waitersCount > 0);
621 LeaveCriticalSection(&condState->waitersCountLock);
622
623 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
624 // down a notch.
625 if (haveWaiters)
626 ReleaseSemaphore(condState->sema, 1, 0);
627
628 // Release internal mutex.
629 ReleaseMutex(condState->internalMutex);
630}
631
632/*
633 * Signal the condition variable, allowing all threads to continue.
634 *
635 * First we have to wake up all threads waiting on the semaphore, then
636 * we wait until all of the threads have actually been woken before
637 * releasing the internal mutex. This ensures that all threads are woken.
638 */
639void Condition::broadcast()
640{
641 WinCondition* condState = (WinCondition*) mState;
642
643 // Lock the internal mutex. This keeps the guys we're waking up
644 // from getting too far.
645 WaitForSingleObject(condState->internalMutex, INFINITE);
646
647 EnterCriticalSection(&condState->waitersCountLock);
648 bool haveWaiters = false;
649
650 if (condState->waitersCount > 0) {
651 haveWaiters = true;
652 condState->wasBroadcast = true;
653 }
654
655 if (haveWaiters) {
656 // Wake up all the waiters.
657 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
658
659 LeaveCriticalSection(&condState->waitersCountLock);
660
661 // Wait for all awakened threads to acquire the counting semaphore.
662 // The last guy who was waiting sets this.
663 WaitForSingleObject(condState->waitersDone, INFINITE);
664
665 // Reset wasBroadcast. (No crit section needed because nobody
666 // else can wake up to poke at it.)
667 condState->wasBroadcast = 0;
668 } else {
669 // nothing to do
670 LeaveCriticalSection(&condState->waitersCountLock);
671 }
672
673 // Release internal mutex.
674 ReleaseMutex(condState->internalMutex);
675}
676
677#else
678#error "condition variables not supported on this platform"
679#endif
680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681// ----------------------------------------------------------------------------
682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683/*
684 * This is our thread object!
685 */
686
687Thread::Thread(bool canCallJava)
688 : mCanCallJava(canCallJava),
689 mThread(thread_id_t(-1)),
690 mLock("Thread::mLock"),
691 mStatus(NO_ERROR),
692 mExitPending(false), mRunning(false)
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800693#ifdef HAVE_ANDROID_OS
694 , mTid(-1)
695#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696{
697}
698
699Thread::~Thread()
700{
701}
702
703status_t Thread::readyToRun()
704{
705 return NO_ERROR;
706}
707
708status_t Thread::run(const char* name, int32_t priority, size_t stack)
709{
710 Mutex::Autolock _l(mLock);
711
712 if (mRunning) {
713 // thread already started
714 return INVALID_OPERATION;
715 }
716
717 // reset status and exitPending to their default value, so we can
718 // try again after an error happened (either below, or in readyToRun())
719 mStatus = NO_ERROR;
720 mExitPending = false;
721 mThread = thread_id_t(-1);
722
723 // hold a strong reference on ourself
724 mHoldSelf = this;
725
The Android Open Source Project4df24232009-03-05 14:34:35 -0800726 mRunning = true;
727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 bool res;
729 if (mCanCallJava) {
730 res = createThreadEtc(_threadLoop,
731 this, name, priority, stack, &mThread);
732 } else {
733 res = androidCreateRawThreadEtc(_threadLoop,
734 this, name, priority, stack, &mThread);
735 }
736
737 if (res == false) {
738 mStatus = UNKNOWN_ERROR; // something happened!
739 mRunning = false;
740 mThread = thread_id_t(-1);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800741 mHoldSelf.clear(); // "this" may have gone away after this.
742
743 return UNKNOWN_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 }
745
The Android Open Source Project4df24232009-03-05 14:34:35 -0800746 // Do not refer to mStatus here: The thread is already running (may, in fact
747 // already have exited with a valid mStatus result). The NO_ERROR indication
748 // here merely indicates successfully starting the thread and does not
749 // imply successful termination/execution.
750 return NO_ERROR;
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800751
752 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753}
754
755int Thread::_threadLoop(void* user)
756{
757 Thread* const self = static_cast<Thread*>(user);
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 sp<Thread> strong(self->mHoldSelf);
760 wp<Thread> weak(strong);
761 self->mHoldSelf.clear();
762
Kenny Rootbb9d3942011-02-16 10:13:53 -0800763#ifdef HAVE_ANDROID_OS
Mathias Agopiand42bd872009-09-09 02:38:13 -0700764 // this is very useful for debugging with gdb
765 self->mTid = gettid();
766#endif
767
The Android Open Source Project4df24232009-03-05 14:34:35 -0800768 bool first = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
770 do {
The Android Open Source Project4df24232009-03-05 14:34:35 -0800771 bool result;
772 if (first) {
773 first = false;
774 self->mStatus = self->readyToRun();
775 result = (self->mStatus == NO_ERROR);
776
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800777 if (result && !self->exitPending()) {
The Android Open Source Project4df24232009-03-05 14:34:35 -0800778 // Binder threads (and maybe others) rely on threadLoop
779 // running at least once after a successful ::readyToRun()
780 // (unless, of course, the thread has already been asked to exit
781 // at that point).
782 // This is because threads are essentially used like this:
783 // (new ThreadSubclass())->run();
784 // The caller therefore does not retain a strong reference to
785 // the thread and the thread would simply disappear after the
786 // successful ::readyToRun() call instead of entering the
787 // threadLoop at least once.
788 result = self->threadLoop();
789 }
790 } else {
791 result = self->threadLoop();
792 }
793
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800794 // establish a scope for mLock
795 {
796 Mutex::Autolock _l(self->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 if (result == false || self->mExitPending) {
798 self->mExitPending = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 self->mRunning = false;
Eric Laurent730ba192011-01-04 11:58:04 -0800800 // clear thread ID so that requestExitAndWait() does not exit if
801 // called by a new thread using the same thread ID as this one.
802 self->mThread = thread_id_t(-1);
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800803 // note that interested observers blocked in requestExitAndWait are
804 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopiand42bd872009-09-09 02:38:13 -0700805 self->mThreadExitedCondition.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 break;
807 }
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809
810 // Release our strong reference, to let a chance to the thread
811 // to die a peaceful death.
812 strong.clear();
Mathias Agopiand42bd872009-09-09 02:38:13 -0700813 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 strong = weak.promote();
815 } while(strong != 0);
816
817 return 0;
818}
819
820void Thread::requestExit()
821{
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800822 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 mExitPending = true;
824}
825
826status_t Thread::requestExitAndWait()
827{
Glenn Kasten9dbd7d82011-06-02 08:59:28 -0700828 Mutex::Autolock _l(mLock);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800829 if (mThread == getThreadId()) {
830 LOGW(
831 "Thread (this=%p): don't call waitForExit() from this "
832 "Thread object's thread. It's a guaranteed deadlock!",
833 this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834
The Android Open Source Project4df24232009-03-05 14:34:35 -0800835 return WOULD_BLOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800837
Glenn Kasten9dbd7d82011-06-02 08:59:28 -0700838 mExitPending = true;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800839
The Android Open Source Project4df24232009-03-05 14:34:35 -0800840 while (mRunning == true) {
841 mThreadExitedCondition.wait(mLock);
842 }
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800843 // This next line is probably not needed any more, but is being left for
844 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project4df24232009-03-05 14:34:35 -0800845 mExitPending = false;
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 return mStatus;
848}
849
Glenn Kasten697283e2011-06-23 12:55:29 -0700850status_t Thread::join()
851{
852 Mutex::Autolock _l(mLock);
853 if (mThread == getThreadId()) {
854 LOGW(
855 "Thread (this=%p): don't call join() from this "
856 "Thread object's thread. It's a guaranteed deadlock!",
857 this);
858
859 return WOULD_BLOCK;
860 }
861
862 while (mRunning == true) {
863 mThreadExitedCondition.wait(mLock);
864 }
865
866 return mStatus;
867}
868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869bool Thread::exitPending() const
870{
Glenn Kastenc2b3cda2011-02-01 11:32:29 -0800871 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 return mExitPending;
873}
874
875
876
877}; // namespace android