blob: df2fb1994d014eb5346de325168072690533e394 [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);
164 if (result != 0) {
165 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
166 "(android threadPriority=%d)",
167 entryFunction, result, errno, threadPriority);
168 return 0;
169 }
170
171 if (threadId != NULL) {
172 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
173 }
174 return 1;
175}
176
177android_thread_id_t androidGetThreadId()
178{
179 return (android_thread_id_t)pthread_self();
180}
181
182// ----------------------------------------------------------------------------
183#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184// ----------------------------------------------------------------------------
185
186/*
187 * Trampoline to make us __stdcall-compliant.
188 *
189 * We're expected to delete "vDetails" when we're done.
190 */
191struct threadDetails {
192 int (*func)(void*);
193 void* arg;
194};
195static __stdcall unsigned int threadIntermediary(void* vDetails)
196{
197 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
198 int result;
199
200 result = (*(pDetails->func))(pDetails->arg);
201
202 delete pDetails;
203
204 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
205 return (unsigned int) result;
206}
207
208/*
209 * Create and run a new thread.
210 */
211static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
212{
213 HANDLE hThread;
214 struct threadDetails* pDetails = new threadDetails; // must be on heap
215 unsigned int thrdaddr;
216
217 pDetails->func = fn;
218 pDetails->arg = arg;
219
220#if defined(HAVE__BEGINTHREADEX)
221 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
222 &thrdaddr);
223 if (hThread == 0)
224#elif defined(HAVE_CREATETHREAD)
225 hThread = CreateThread(NULL, 0,
226 (LPTHREAD_START_ROUTINE) threadIntermediary,
227 (void*) pDetails, 0, (DWORD*) &thrdaddr);
228 if (hThread == NULL)
229#endif
230 {
231 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
232 return false;
233 }
234
235#if defined(HAVE_CREATETHREAD)
236 /* close the management handle */
237 CloseHandle(hThread);
238#endif
239
240 if (id != NULL) {
241 *id = (android_thread_id_t)thrdaddr;
242 }
243
244 return true;
245}
246
247int androidCreateRawThreadEtc(android_thread_func_t fn,
248 void *userData,
249 const char* threadName,
250 int32_t threadPriority,
251 size_t threadStackSize,
252 android_thread_id_t *threadId)
253{
254 return doCreateThread( fn, userData, threadId);
255}
256
257android_thread_id_t androidGetThreadId()
258{
259 return (android_thread_id_t)GetCurrentThreadId();
260}
261
262// ----------------------------------------------------------------------------
263#else
264#error "Threads not supported"
265#endif
266
267// ----------------------------------------------------------------------------
268
The Android Open Source Project9066cfe2009-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
Dianne Hackborn887f3552009-12-07 17:59:37 -0800298pid_t androidGetTid()
299{
300#ifdef HAVE_GETTID
301 return gettid();
302#else
303 return getpid();
304#endif
305}
306
307int androidSetThreadSchedulingGroup(pid_t tid, int grp)
308{
309 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
310 return BAD_VALUE;
311 }
312
Dianne Hackbornafbeb312009-12-08 19:45:59 -0800313#if defined(HAVE_PTHREADS)
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700314 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
315 if (gDoSchedulingGroup) {
316 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
317 SP_BACKGROUND : SP_FOREGROUND)) {
318 return PERMISSION_DENIED;
319 }
Dianne Hackborn887f3552009-12-07 17:59:37 -0800320 }
Dianne Hackbornafbeb312009-12-08 19:45:59 -0800321#endif
Dianne Hackborn887f3552009-12-07 17:59:37 -0800322
323 return NO_ERROR;
324}
325
326int androidSetThreadPriority(pid_t tid, int pri)
327{
328 int rc = 0;
Dianne Hackbornafbeb312009-12-08 19:45:59 -0800329
330#if defined(HAVE_PTHREADS)
Dianne Hackborn887f3552009-12-07 17:59:37 -0800331 int lasterr = 0;
332
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700333 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
334 if (gDoSchedulingGroup) {
Glenn Kasten1d24aaa2011-06-14 10:35:34 -0700335 // set_sched_policy does not support tid == 0
336 int policy_tid;
337 if (tid == 0) {
338 policy_tid = androidGetTid();
339 } else {
340 policy_tid = tid;
341 }
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700342 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten1d24aaa2011-06-14 10:35:34 -0700343 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700344 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten1d24aaa2011-06-14 10:35:34 -0700345 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn84bb52e2010-09-03 17:07:07 -0700346 }
Dianne Hackborn887f3552009-12-07 17:59:37 -0800347 }
348
349 if (rc) {
350 lasterr = errno;
351 }
352
353 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
354 rc = INVALID_OPERATION;
355 } else {
356 errno = lasterr;
357 }
Dianne Hackborn06fb2c12009-12-08 16:38:01 -0800358#endif
Dianne Hackborn887f3552009-12-07 17:59:37 -0800359
360 return rc;
361}
362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363namespace android {
364
365/*
366 * ===========================================================================
367 * Mutex class
368 * ===========================================================================
369 */
370
Mathias Agopianb1c4ca52009-07-12 23:11:20 -0700371#if defined(HAVE_PTHREADS)
372// implemented as inlines in threads.h
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374
375Mutex::Mutex()
376{
377 HANDLE hMutex;
378
379 assert(sizeof(hMutex) == sizeof(mState));
380
381 hMutex = CreateMutex(NULL, FALSE, NULL);
382 mState = (void*) hMutex;
383}
384
385Mutex::Mutex(const char* name)
386{
387 // XXX: name not used for now
388 HANDLE hMutex;
389
David 'Digit' Turner078a2752009-08-01 00:20:17 +0200390 assert(sizeof(hMutex) == sizeof(mState));
391
392 hMutex = CreateMutex(NULL, FALSE, NULL);
393 mState = (void*) hMutex;
394}
395
396Mutex::Mutex(int type, const char* name)
397{
398 // XXX: type and name not used for now
399 HANDLE hMutex;
400
401 assert(sizeof(hMutex) == sizeof(mState));
402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 hMutex = CreateMutex(NULL, FALSE, NULL);
404 mState = (void*) hMutex;
405}
406
407Mutex::~Mutex()
408{
409 CloseHandle((HANDLE) mState);
410}
411
412status_t Mutex::lock()
413{
414 DWORD dwWaitResult;
415 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
416 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
417}
418
419void Mutex::unlock()
420{
421 if (!ReleaseMutex((HANDLE) mState))
422 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
423}
424
425status_t Mutex::tryLock()
426{
427 DWORD dwWaitResult;
428
429 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
430 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
431 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
432 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
433}
434
435#else
436#error "Somebody forgot to implement threads for this platform."
437#endif
438
439
440/*
441 * ===========================================================================
442 * Condition class
443 * ===========================================================================
444 */
445
Mathias Agopianb1c4ca52009-07-12 23:11:20 -0700446#if defined(HAVE_PTHREADS)
447// implemented as inlines in threads.h
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449
450/*
451 * Windows doesn't have a condition variable solution. It's possible
452 * to create one, but it's easy to get it wrong. For a discussion, and
453 * the origin of this implementation, see:
454 *
455 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
456 *
457 * The implementation shown on the page does NOT follow POSIX semantics.
458 * As an optimization they require acquiring the external mutex before
459 * calling signal() and broadcast(), whereas POSIX only requires grabbing
460 * it before calling wait(). The implementation here has been un-optimized
461 * to have the correct behavior.
462 */
463typedef struct WinCondition {
464 // Number of waiting threads.
465 int waitersCount;
466
467 // Serialize access to waitersCount.
468 CRITICAL_SECTION waitersCountLock;
469
470 // Semaphore used to queue up threads waiting for the condition to
471 // become signaled.
472 HANDLE sema;
473
474 // An auto-reset event used by the broadcast/signal thread to wait
475 // for all the waiting thread(s) to wake up and be released from
476 // the semaphore.
477 HANDLE waitersDone;
478
479 // This mutex wouldn't be necessary if we required that the caller
480 // lock the external mutex before calling signal() and broadcast().
481 // I'm trying to mimic pthread semantics though.
482 HANDLE internalMutex;
483
484 // Keeps track of whether we were broadcasting or signaling. This
485 // allows us to optimize the code if we're just signaling.
486 bool wasBroadcast;
487
488 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
489 {
490 // Increment the wait count, avoiding race conditions.
491 EnterCriticalSection(&condState->waitersCountLock);
492 condState->waitersCount++;
493 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
494 // condState->waitersCount, getThreadId());
495 LeaveCriticalSection(&condState->waitersCountLock);
496
497 DWORD timeout = INFINITE;
498 if (abstime) {
499 nsecs_t reltime = *abstime - systemTime();
500 if (reltime < 0)
501 reltime = 0;
502 timeout = reltime/1000000;
503 }
504
505 // Atomically release the external mutex and wait on the semaphore.
506 DWORD res =
507 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
508
509 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
510
511 // Reacquire lock to avoid race conditions.
512 EnterCriticalSection(&condState->waitersCountLock);
513
514 // No longer waiting.
515 condState->waitersCount--;
516
517 // Check to see if we're the last waiter after a broadcast.
518 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
519
520 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
521 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
522
523 LeaveCriticalSection(&condState->waitersCountLock);
524
525 // If we're the last waiter thread during this particular broadcast
526 // then signal broadcast() that we're all awake. It'll drop the
527 // internal mutex.
528 if (lastWaiter) {
529 // Atomically signal the "waitersDone" event and wait until we
530 // can acquire the internal mutex. We want to do this in one step
531 // because it ensures that everybody is in the mutex FIFO before
532 // any thread has a chance to run. Without it, another thread
533 // could wake up, do work, and hop back in ahead of us.
534 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
535 INFINITE, FALSE);
536 } else {
537 // Grab the internal mutex.
538 WaitForSingleObject(condState->internalMutex, INFINITE);
539 }
540
541 // Release the internal and grab the external.
542 ReleaseMutex(condState->internalMutex);
543 WaitForSingleObject(hMutex, INFINITE);
544
545 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
546 }
547} WinCondition;
548
549/*
550 * Constructor. Set up the WinCondition stuff.
551 */
552Condition::Condition()
553{
554 WinCondition* condState = new WinCondition;
555
556 condState->waitersCount = 0;
557 condState->wasBroadcast = false;
558 // semaphore: no security, initial value of 0
559 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
560 InitializeCriticalSection(&condState->waitersCountLock);
561 // auto-reset event, not signaled initially
562 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
563 // used so we don't have to lock external mutex on signal/broadcast
564 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
565
566 mState = condState;
567}
568
569/*
570 * Destructor. Free Windows resources as well as our allocated storage.
571 */
572Condition::~Condition()
573{
574 WinCondition* condState = (WinCondition*) mState;
575 if (condState != NULL) {
576 CloseHandle(condState->sema);
577 CloseHandle(condState->waitersDone);
578 delete condState;
579 }
580}
581
582
583status_t Condition::wait(Mutex& mutex)
584{
585 WinCondition* condState = (WinCondition*) mState;
586 HANDLE hMutex = (HANDLE) mutex.mState;
587
588 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
589}
590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
592{
David 'Digit' Turner078a2752009-08-01 00:20:17 +0200593 WinCondition* condState = (WinCondition*) mState;
594 HANDLE hMutex = (HANDLE) mutex.mState;
595 nsecs_t absTime = systemTime()+reltime;
596
597 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598}
599
600/*
601 * Signal the condition variable, allowing one thread to continue.
602 */
603void Condition::signal()
604{
605 WinCondition* condState = (WinCondition*) mState;
606
607 // Lock the internal mutex. This ensures that we don't clash with
608 // broadcast().
609 WaitForSingleObject(condState->internalMutex, INFINITE);
610
611 EnterCriticalSection(&condState->waitersCountLock);
612 bool haveWaiters = (condState->waitersCount > 0);
613 LeaveCriticalSection(&condState->waitersCountLock);
614
615 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
616 // down a notch.
617 if (haveWaiters)
618 ReleaseSemaphore(condState->sema, 1, 0);
619
620 // Release internal mutex.
621 ReleaseMutex(condState->internalMutex);
622}
623
624/*
625 * Signal the condition variable, allowing all threads to continue.
626 *
627 * First we have to wake up all threads waiting on the semaphore, then
628 * we wait until all of the threads have actually been woken before
629 * releasing the internal mutex. This ensures that all threads are woken.
630 */
631void Condition::broadcast()
632{
633 WinCondition* condState = (WinCondition*) mState;
634
635 // Lock the internal mutex. This keeps the guys we're waking up
636 // from getting too far.
637 WaitForSingleObject(condState->internalMutex, INFINITE);
638
639 EnterCriticalSection(&condState->waitersCountLock);
640 bool haveWaiters = false;
641
642 if (condState->waitersCount > 0) {
643 haveWaiters = true;
644 condState->wasBroadcast = true;
645 }
646
647 if (haveWaiters) {
648 // Wake up all the waiters.
649 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
650
651 LeaveCriticalSection(&condState->waitersCountLock);
652
653 // Wait for all awakened threads to acquire the counting semaphore.
654 // The last guy who was waiting sets this.
655 WaitForSingleObject(condState->waitersDone, INFINITE);
656
657 // Reset wasBroadcast. (No crit section needed because nobody
658 // else can wake up to poke at it.)
659 condState->wasBroadcast = 0;
660 } else {
661 // nothing to do
662 LeaveCriticalSection(&condState->waitersCountLock);
663 }
664
665 // Release internal mutex.
666 ReleaseMutex(condState->internalMutex);
667}
668
669#else
670#error "condition variables not supported on this platform"
671#endif
672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673// ----------------------------------------------------------------------------
674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675/*
676 * This is our thread object!
677 */
678
679Thread::Thread(bool canCallJava)
680 : mCanCallJava(canCallJava),
681 mThread(thread_id_t(-1)),
682 mLock("Thread::mLock"),
683 mStatus(NO_ERROR),
684 mExitPending(false), mRunning(false)
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800685#ifdef HAVE_ANDROID_OS
686 , mTid(-1)
687#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688{
689}
690
691Thread::~Thread()
692{
693}
694
695status_t Thread::readyToRun()
696{
697 return NO_ERROR;
698}
699
700status_t Thread::run(const char* name, int32_t priority, size_t stack)
701{
702 Mutex::Autolock _l(mLock);
703
704 if (mRunning) {
705 // thread already started
706 return INVALID_OPERATION;
707 }
708
709 // reset status and exitPending to their default value, so we can
710 // try again after an error happened (either below, or in readyToRun())
711 mStatus = NO_ERROR;
712 mExitPending = false;
713 mThread = thread_id_t(-1);
714
715 // hold a strong reference on ourself
716 mHoldSelf = this;
717
The Android Open Source Project4df24232009-03-05 14:34:35 -0800718 mRunning = true;
719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 bool res;
721 if (mCanCallJava) {
722 res = createThreadEtc(_threadLoop,
723 this, name, priority, stack, &mThread);
724 } else {
725 res = androidCreateRawThreadEtc(_threadLoop,
726 this, name, priority, stack, &mThread);
727 }
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800728 // The new thread wakes up at _threadLoop, but immediately blocks on mLock
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729
730 if (res == false) {
731 mStatus = UNKNOWN_ERROR; // something happened!
732 mRunning = false;
733 mThread = thread_id_t(-1);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800734 mHoldSelf.clear(); // "this" may have gone away after this.
735
736 return UNKNOWN_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 }
738
The Android Open Source Project4df24232009-03-05 14:34:35 -0800739 // Do not refer to mStatus here: The thread is already running (may, in fact
740 // already have exited with a valid mStatus result). The NO_ERROR indication
741 // here merely indicates successfully starting the thread and does not
742 // imply successful termination/execution.
743 return NO_ERROR;
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800744
745 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746}
747
748int Thread::_threadLoop(void* user)
749{
750 Thread* const self = static_cast<Thread*>(user);
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800751
752 // force a memory barrier before reading any fields, in particular mHoldSelf
753 {
754 Mutex::Autolock _l(self->mLock);
755 }
756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 sp<Thread> strong(self->mHoldSelf);
758 wp<Thread> weak(strong);
759 self->mHoldSelf.clear();
760
Kenny Rootbb9d3942011-02-16 10:13:53 -0800761#ifdef HAVE_ANDROID_OS
Mathias Agopiand42bd872009-09-09 02:38:13 -0700762 // this is very useful for debugging with gdb
763 self->mTid = gettid();
764#endif
765
The Android Open Source Project4df24232009-03-05 14:34:35 -0800766 bool first = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
768 do {
The Android Open Source Project4df24232009-03-05 14:34:35 -0800769 bool result;
770 if (first) {
771 first = false;
772 self->mStatus = self->readyToRun();
773 result = (self->mStatus == NO_ERROR);
774
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800775 if (result && !self->exitPending()) {
The Android Open Source Project4df24232009-03-05 14:34:35 -0800776 // Binder threads (and maybe others) rely on threadLoop
777 // running at least once after a successful ::readyToRun()
778 // (unless, of course, the thread has already been asked to exit
779 // at that point).
780 // This is because threads are essentially used like this:
781 // (new ThreadSubclass())->run();
782 // The caller therefore does not retain a strong reference to
783 // the thread and the thread would simply disappear after the
784 // successful ::readyToRun() call instead of entering the
785 // threadLoop at least once.
786 result = self->threadLoop();
787 }
788 } else {
789 result = self->threadLoop();
790 }
791
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800792 // establish a scope for mLock
793 {
794 Mutex::Autolock _l(self->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 if (result == false || self->mExitPending) {
796 self->mExitPending = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 self->mRunning = false;
Eric Laurent730ba192011-01-04 11:58:04 -0800798 // clear thread ID so that requestExitAndWait() does not exit if
799 // called by a new thread using the same thread ID as this one.
800 self->mThread = thread_id_t(-1);
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800801 // note that interested observers blocked in requestExitAndWait are
802 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopiand42bd872009-09-09 02:38:13 -0700803 self->mThreadExitedCondition.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 break;
805 }
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807
808 // Release our strong reference, to let a chance to the thread
809 // to die a peaceful death.
810 strong.clear();
Mathias Agopiand42bd872009-09-09 02:38:13 -0700811 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 strong = weak.promote();
813 } while(strong != 0);
814
815 return 0;
816}
817
818void Thread::requestExit()
819{
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800820 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 mExitPending = true;
822}
823
824status_t Thread::requestExitAndWait()
825{
The Android Open Source Project4df24232009-03-05 14:34:35 -0800826 if (mThread == getThreadId()) {
827 LOGW(
828 "Thread (this=%p): don't call waitForExit() from this "
829 "Thread object's thread. It's a guaranteed deadlock!",
830 this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831
The Android Open Source Project4df24232009-03-05 14:34:35 -0800832 return WOULD_BLOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800834
835 requestExit();
836
837 Mutex::Autolock _l(mLock);
838 while (mRunning == true) {
839 mThreadExitedCondition.wait(mLock);
840 }
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800841 // This next line is probably not needed any more, but is being left for
842 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project4df24232009-03-05 14:34:35 -0800843 mExitPending = false;
844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 return mStatus;
846}
847
848bool Thread::exitPending() const
849{
Glenn Kastenc2b3cda02011-02-01 11:32:29 -0800850 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 return mExitPending;
852}
853
854
855
856}; // namespace android