blob: 00f9943bfe833b58bae6a8ca7cb1b96f775fb1f1 [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project7a4c8392009-03-05 14:34:35 -080017// #define LOG_NDEBUG 0
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080018#define LOG_TAG "libutils.threads"
19
20#include <utils/threads.h>
21#include <utils/Log.h>
22
Dianne Hackborn235af972009-12-07 17:59:37 -080023#include <cutils/sched_policy.h>
24
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025#include <stdio.h>
26#include <stdlib.h>
27#include <memory.h>
28#include <errno.h>
29#include <assert.h>
30#include <unistd.h>
31
32#if defined(HAVE_PTHREADS)
33# include <pthread.h>
34# include <sched.h>
35# include <sys/resource.h>
36#elif defined(HAVE_WIN32_THREADS)
37# include <windows.h>
38# include <stdint.h>
39# include <process.h>
40# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
41#endif
42
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080043#if defined(HAVE_PRCTL)
44#include <sys/prctl.h>
45#endif
46
47/*
48 * ===========================================================================
49 * Thread wrappers
50 * ===========================================================================
51 */
52
53using namespace android;
54
55// ----------------------------------------------------------------------------
56#if defined(HAVE_PTHREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080057// ----------------------------------------------------------------------------
58
59/*
60 * Create and run a new thead.
61 *
62 * We create it "detached", so it cleans up after itself.
63 */
64
65typedef void* (*android_pthread_entry)(void*);
66
67struct thread_data_t {
68 thread_func_t entryFunction;
69 void* userData;
70 int priority;
71 char * threadName;
72
73 // we use this trampoline when we need to set the priority with
74 // nice/setpriority.
75 static int trampoline(const thread_data_t* t) {
76 thread_func_t f = t->entryFunction;
77 void* u = t->userData;
78 int prio = t->priority;
79 char * name = t->threadName;
80 delete t;
81 setpriority(PRIO_PROCESS, 0, prio);
82 if (name) {
83#if defined(HAVE_PRCTL)
84 // Mac OS doesn't have this, and we build libutil for the host too
85 int hasAt = 0;
86 int hasDot = 0;
87 char *s = name;
88 while (*s) {
89 if (*s == '.') hasDot = 1;
90 else if (*s == '@') hasAt = 1;
91 s++;
92 }
93 int len = s - name;
94 if (len < 15 || hasAt || !hasDot) {
95 s = name;
96 } else {
97 s = name + len - 15;
98 }
99 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
100#endif
101 free(name);
102 }
103 return f(u);
104 }
105};
106
107int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
108 void *userData,
109 const char* threadName,
110 int32_t threadPriority,
111 size_t threadStackSize,
112 android_thread_id_t *threadId)
113{
114 pthread_attr_t attr;
115 pthread_attr_init(&attr);
116 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
117
118#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
119 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
120 // We could avoid the trampoline if there was a way to get to the
121 // android_thread_id_t (pid) from pthread_t
122 thread_data_t* t = new thread_data_t;
123 t->priority = threadPriority;
124 t->threadName = threadName ? strdup(threadName) : NULL;
125 t->entryFunction = entryFunction;
126 t->userData = userData;
127 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
128 userData = t;
129 }
130#endif
131
132 if (threadStackSize) {
133 pthread_attr_setstacksize(&attr, threadStackSize);
134 }
135
136 errno = 0;
137 pthread_t thread;
138 int result = pthread_create(&thread, &attr,
139 (android_pthread_entry)entryFunction, userData);
140 if (result != 0) {
141 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
142 "(android threadPriority=%d)",
143 entryFunction, result, errno, threadPriority);
144 return 0;
145 }
146
147 if (threadId != NULL) {
148 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
149 }
150 return 1;
151}
152
153android_thread_id_t androidGetThreadId()
154{
155 return (android_thread_id_t)pthread_self();
156}
157
158// ----------------------------------------------------------------------------
159#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800160// ----------------------------------------------------------------------------
161
162/*
163 * Trampoline to make us __stdcall-compliant.
164 *
165 * We're expected to delete "vDetails" when we're done.
166 */
167struct threadDetails {
168 int (*func)(void*);
169 void* arg;
170};
171static __stdcall unsigned int threadIntermediary(void* vDetails)
172{
173 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
174 int result;
175
176 result = (*(pDetails->func))(pDetails->arg);
177
178 delete pDetails;
179
180 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
181 return (unsigned int) result;
182}
183
184/*
185 * Create and run a new thread.
186 */
187static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
188{
189 HANDLE hThread;
190 struct threadDetails* pDetails = new threadDetails; // must be on heap
191 unsigned int thrdaddr;
192
193 pDetails->func = fn;
194 pDetails->arg = arg;
195
196#if defined(HAVE__BEGINTHREADEX)
197 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
198 &thrdaddr);
199 if (hThread == 0)
200#elif defined(HAVE_CREATETHREAD)
201 hThread = CreateThread(NULL, 0,
202 (LPTHREAD_START_ROUTINE) threadIntermediary,
203 (void*) pDetails, 0, (DWORD*) &thrdaddr);
204 if (hThread == NULL)
205#endif
206 {
207 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
208 return false;
209 }
210
211#if defined(HAVE_CREATETHREAD)
212 /* close the management handle */
213 CloseHandle(hThread);
214#endif
215
216 if (id != NULL) {
217 *id = (android_thread_id_t)thrdaddr;
218 }
219
220 return true;
221}
222
223int androidCreateRawThreadEtc(android_thread_func_t fn,
224 void *userData,
225 const char* threadName,
226 int32_t threadPriority,
227 size_t threadStackSize,
228 android_thread_id_t *threadId)
229{
230 return doCreateThread( fn, userData, threadId);
231}
232
233android_thread_id_t androidGetThreadId()
234{
235 return (android_thread_id_t)GetCurrentThreadId();
236}
237
238// ----------------------------------------------------------------------------
239#else
240#error "Threads not supported"
241#endif
242
243// ----------------------------------------------------------------------------
244
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800245int androidCreateThread(android_thread_func_t fn, void* arg)
246{
247 return createThreadEtc(fn, arg);
248}
249
250int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
251{
252 return createThreadEtc(fn, arg, "android:unnamed_thread",
253 PRIORITY_DEFAULT, 0, id);
254}
255
256static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
257
258int androidCreateThreadEtc(android_thread_func_t entryFunction,
259 void *userData,
260 const char* threadName,
261 int32_t threadPriority,
262 size_t threadStackSize,
263 android_thread_id_t *threadId)
264{
265 return gCreateThreadFn(entryFunction, userData, threadName,
266 threadPriority, threadStackSize, threadId);
267}
268
269void androidSetCreateThreadFunc(android_create_thread_fn func)
270{
271 gCreateThreadFn = func;
272}
273
Dianne Hackborn235af972009-12-07 17:59:37 -0800274pid_t androidGetTid()
275{
276#ifdef HAVE_GETTID
277 return gettid();
278#else
279 return getpid();
280#endif
281}
282
283int androidSetThreadSchedulingGroup(pid_t tid, int grp)
284{
285 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
286 return BAD_VALUE;
287 }
288
289 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
290 SP_BACKGROUND : SP_FOREGROUND)) {
291 return PERMISSION_DENIED;
292 }
293
294 return NO_ERROR;
295}
296
297int androidSetThreadPriority(pid_t tid, int pri)
298{
299 int rc = 0;
300 int lasterr = 0;
301
302 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
303 rc = set_sched_policy(tid, SP_BACKGROUND);
304 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
305 rc = set_sched_policy(tid, SP_FOREGROUND);
306 }
307
308 if (rc) {
309 lasterr = errno;
310 }
311
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800312#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800313 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
314 rc = INVALID_OPERATION;
315 } else {
316 errno = lasterr;
317 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800318#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800319
320 return rc;
321}
322
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800323namespace android {
324
325/*
326 * ===========================================================================
327 * Mutex class
328 * ===========================================================================
329 */
330
Mathias Agopian15554362009-07-12 23:11:20 -0700331#if defined(HAVE_PTHREADS)
332// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800333#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800334
335Mutex::Mutex()
336{
337 HANDLE hMutex;
338
339 assert(sizeof(hMutex) == sizeof(mState));
340
341 hMutex = CreateMutex(NULL, FALSE, NULL);
342 mState = (void*) hMutex;
343}
344
345Mutex::Mutex(const char* name)
346{
347 // XXX: name not used for now
348 HANDLE hMutex;
349
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200350 assert(sizeof(hMutex) == sizeof(mState));
351
352 hMutex = CreateMutex(NULL, FALSE, NULL);
353 mState = (void*) hMutex;
354}
355
356Mutex::Mutex(int type, const char* name)
357{
358 // XXX: type and name not used for now
359 HANDLE hMutex;
360
361 assert(sizeof(hMutex) == sizeof(mState));
362
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800363 hMutex = CreateMutex(NULL, FALSE, NULL);
364 mState = (void*) hMutex;
365}
366
367Mutex::~Mutex()
368{
369 CloseHandle((HANDLE) mState);
370}
371
372status_t Mutex::lock()
373{
374 DWORD dwWaitResult;
375 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
376 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
377}
378
379void Mutex::unlock()
380{
381 if (!ReleaseMutex((HANDLE) mState))
382 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
383}
384
385status_t Mutex::tryLock()
386{
387 DWORD dwWaitResult;
388
389 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
390 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
391 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
392 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
393}
394
395#else
396#error "Somebody forgot to implement threads for this platform."
397#endif
398
399
400/*
401 * ===========================================================================
402 * Condition class
403 * ===========================================================================
404 */
405
Mathias Agopian15554362009-07-12 23:11:20 -0700406#if defined(HAVE_PTHREADS)
407// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800408#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800409
410/*
411 * Windows doesn't have a condition variable solution. It's possible
412 * to create one, but it's easy to get it wrong. For a discussion, and
413 * the origin of this implementation, see:
414 *
415 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
416 *
417 * The implementation shown on the page does NOT follow POSIX semantics.
418 * As an optimization they require acquiring the external mutex before
419 * calling signal() and broadcast(), whereas POSIX only requires grabbing
420 * it before calling wait(). The implementation here has been un-optimized
421 * to have the correct behavior.
422 */
423typedef struct WinCondition {
424 // Number of waiting threads.
425 int waitersCount;
426
427 // Serialize access to waitersCount.
428 CRITICAL_SECTION waitersCountLock;
429
430 // Semaphore used to queue up threads waiting for the condition to
431 // become signaled.
432 HANDLE sema;
433
434 // An auto-reset event used by the broadcast/signal thread to wait
435 // for all the waiting thread(s) to wake up and be released from
436 // the semaphore.
437 HANDLE waitersDone;
438
439 // This mutex wouldn't be necessary if we required that the caller
440 // lock the external mutex before calling signal() and broadcast().
441 // I'm trying to mimic pthread semantics though.
442 HANDLE internalMutex;
443
444 // Keeps track of whether we were broadcasting or signaling. This
445 // allows us to optimize the code if we're just signaling.
446 bool wasBroadcast;
447
448 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
449 {
450 // Increment the wait count, avoiding race conditions.
451 EnterCriticalSection(&condState->waitersCountLock);
452 condState->waitersCount++;
453 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
454 // condState->waitersCount, getThreadId());
455 LeaveCriticalSection(&condState->waitersCountLock);
456
457 DWORD timeout = INFINITE;
458 if (abstime) {
459 nsecs_t reltime = *abstime - systemTime();
460 if (reltime < 0)
461 reltime = 0;
462 timeout = reltime/1000000;
463 }
464
465 // Atomically release the external mutex and wait on the semaphore.
466 DWORD res =
467 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
468
469 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
470
471 // Reacquire lock to avoid race conditions.
472 EnterCriticalSection(&condState->waitersCountLock);
473
474 // No longer waiting.
475 condState->waitersCount--;
476
477 // Check to see if we're the last waiter after a broadcast.
478 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
479
480 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
481 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
482
483 LeaveCriticalSection(&condState->waitersCountLock);
484
485 // If we're the last waiter thread during this particular broadcast
486 // then signal broadcast() that we're all awake. It'll drop the
487 // internal mutex.
488 if (lastWaiter) {
489 // Atomically signal the "waitersDone" event and wait until we
490 // can acquire the internal mutex. We want to do this in one step
491 // because it ensures that everybody is in the mutex FIFO before
492 // any thread has a chance to run. Without it, another thread
493 // could wake up, do work, and hop back in ahead of us.
494 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
495 INFINITE, FALSE);
496 } else {
497 // Grab the internal mutex.
498 WaitForSingleObject(condState->internalMutex, INFINITE);
499 }
500
501 // Release the internal and grab the external.
502 ReleaseMutex(condState->internalMutex);
503 WaitForSingleObject(hMutex, INFINITE);
504
505 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
506 }
507} WinCondition;
508
509/*
510 * Constructor. Set up the WinCondition stuff.
511 */
512Condition::Condition()
513{
514 WinCondition* condState = new WinCondition;
515
516 condState->waitersCount = 0;
517 condState->wasBroadcast = false;
518 // semaphore: no security, initial value of 0
519 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
520 InitializeCriticalSection(&condState->waitersCountLock);
521 // auto-reset event, not signaled initially
522 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
523 // used so we don't have to lock external mutex on signal/broadcast
524 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
525
526 mState = condState;
527}
528
529/*
530 * Destructor. Free Windows resources as well as our allocated storage.
531 */
532Condition::~Condition()
533{
534 WinCondition* condState = (WinCondition*) mState;
535 if (condState != NULL) {
536 CloseHandle(condState->sema);
537 CloseHandle(condState->waitersDone);
538 delete condState;
539 }
540}
541
542
543status_t Condition::wait(Mutex& mutex)
544{
545 WinCondition* condState = (WinCondition*) mState;
546 HANDLE hMutex = (HANDLE) mutex.mState;
547
548 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
549}
550
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800551status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
552{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200553 WinCondition* condState = (WinCondition*) mState;
554 HANDLE hMutex = (HANDLE) mutex.mState;
555 nsecs_t absTime = systemTime()+reltime;
556
557 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800558}
559
560/*
561 * Signal the condition variable, allowing one thread to continue.
562 */
563void Condition::signal()
564{
565 WinCondition* condState = (WinCondition*) mState;
566
567 // Lock the internal mutex. This ensures that we don't clash with
568 // broadcast().
569 WaitForSingleObject(condState->internalMutex, INFINITE);
570
571 EnterCriticalSection(&condState->waitersCountLock);
572 bool haveWaiters = (condState->waitersCount > 0);
573 LeaveCriticalSection(&condState->waitersCountLock);
574
575 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
576 // down a notch.
577 if (haveWaiters)
578 ReleaseSemaphore(condState->sema, 1, 0);
579
580 // Release internal mutex.
581 ReleaseMutex(condState->internalMutex);
582}
583
584/*
585 * Signal the condition variable, allowing all threads to continue.
586 *
587 * First we have to wake up all threads waiting on the semaphore, then
588 * we wait until all of the threads have actually been woken before
589 * releasing the internal mutex. This ensures that all threads are woken.
590 */
591void Condition::broadcast()
592{
593 WinCondition* condState = (WinCondition*) mState;
594
595 // Lock the internal mutex. This keeps the guys we're waking up
596 // from getting too far.
597 WaitForSingleObject(condState->internalMutex, INFINITE);
598
599 EnterCriticalSection(&condState->waitersCountLock);
600 bool haveWaiters = false;
601
602 if (condState->waitersCount > 0) {
603 haveWaiters = true;
604 condState->wasBroadcast = true;
605 }
606
607 if (haveWaiters) {
608 // Wake up all the waiters.
609 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
610
611 LeaveCriticalSection(&condState->waitersCountLock);
612
613 // Wait for all awakened threads to acquire the counting semaphore.
614 // The last guy who was waiting sets this.
615 WaitForSingleObject(condState->waitersDone, INFINITE);
616
617 // Reset wasBroadcast. (No crit section needed because nobody
618 // else can wake up to poke at it.)
619 condState->wasBroadcast = 0;
620 } else {
621 // nothing to do
622 LeaveCriticalSection(&condState->waitersCountLock);
623 }
624
625 // Release internal mutex.
626 ReleaseMutex(condState->internalMutex);
627}
628
629#else
630#error "condition variables not supported on this platform"
631#endif
632
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800633// ----------------------------------------------------------------------------
634
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800635/*
636 * This is our thread object!
637 */
638
639Thread::Thread(bool canCallJava)
640 : mCanCallJava(canCallJava),
641 mThread(thread_id_t(-1)),
642 mLock("Thread::mLock"),
643 mStatus(NO_ERROR),
644 mExitPending(false), mRunning(false)
645{
646}
647
648Thread::~Thread()
649{
650}
651
652status_t Thread::readyToRun()
653{
654 return NO_ERROR;
655}
656
657status_t Thread::run(const char* name, int32_t priority, size_t stack)
658{
659 Mutex::Autolock _l(mLock);
660
661 if (mRunning) {
662 // thread already started
663 return INVALID_OPERATION;
664 }
665
666 // reset status and exitPending to their default value, so we can
667 // try again after an error happened (either below, or in readyToRun())
668 mStatus = NO_ERROR;
669 mExitPending = false;
670 mThread = thread_id_t(-1);
671
672 // hold a strong reference on ourself
673 mHoldSelf = this;
674
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800675 mRunning = true;
676
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800677 bool res;
678 if (mCanCallJava) {
679 res = createThreadEtc(_threadLoop,
680 this, name, priority, stack, &mThread);
681 } else {
682 res = androidCreateRawThreadEtc(_threadLoop,
683 this, name, priority, stack, &mThread);
684 }
685
686 if (res == false) {
687 mStatus = UNKNOWN_ERROR; // something happened!
688 mRunning = false;
689 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800690 mHoldSelf.clear(); // "this" may have gone away after this.
691
692 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800693 }
694
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800695 // Do not refer to mStatus here: The thread is already running (may, in fact
696 // already have exited with a valid mStatus result). The NO_ERROR indication
697 // here merely indicates successfully starting the thread and does not
698 // imply successful termination/execution.
699 return NO_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800700}
701
702int Thread::_threadLoop(void* user)
703{
704 Thread* const self = static_cast<Thread*>(user);
705 sp<Thread> strong(self->mHoldSelf);
706 wp<Thread> weak(strong);
707 self->mHoldSelf.clear();
708
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700709#if HAVE_ANDROID_OS
710 // this is very useful for debugging with gdb
711 self->mTid = gettid();
712#endif
713
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800714 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800715
716 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800717 bool result;
718 if (first) {
719 first = false;
720 self->mStatus = self->readyToRun();
721 result = (self->mStatus == NO_ERROR);
722
723 if (result && !self->mExitPending) {
724 // Binder threads (and maybe others) rely on threadLoop
725 // running at least once after a successful ::readyToRun()
726 // (unless, of course, the thread has already been asked to exit
727 // at that point).
728 // This is because threads are essentially used like this:
729 // (new ThreadSubclass())->run();
730 // The caller therefore does not retain a strong reference to
731 // the thread and the thread would simply disappear after the
732 // successful ::readyToRun() call instead of entering the
733 // threadLoop at least once.
734 result = self->threadLoop();
735 }
736 } else {
737 result = self->threadLoop();
738 }
739
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800740 if (result == false || self->mExitPending) {
741 self->mExitPending = true;
742 self->mLock.lock();
743 self->mRunning = false;
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700744 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800745 self->mLock.unlock();
746 break;
747 }
748
749 // Release our strong reference, to let a chance to the thread
750 // to die a peaceful death.
751 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700752 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800753 strong = weak.promote();
754 } while(strong != 0);
755
756 return 0;
757}
758
759void Thread::requestExit()
760{
761 mExitPending = true;
762}
763
764status_t Thread::requestExitAndWait()
765{
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800766 if (mThread == getThreadId()) {
767 LOGW(
768 "Thread (this=%p): don't call waitForExit() from this "
769 "Thread object's thread. It's a guaranteed deadlock!",
770 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800771
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800772 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800773 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800774
775 requestExit();
776
777 Mutex::Autolock _l(mLock);
778 while (mRunning == true) {
779 mThreadExitedCondition.wait(mLock);
780 }
781 mExitPending = false;
782
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800783 return mStatus;
784}
785
786bool Thread::exitPending() const
787{
788 return mExitPending;
789}
790
791
792
793}; // namespace android