blob: 6ca260374a839d1fbb0823d529fd90291813c32c [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
312 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
313 rc = INVALID_OPERATION;
314 } else {
315 errno = lasterr;
316 }
317
318 return rc;
319}
320
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800321namespace android {
322
323/*
324 * ===========================================================================
325 * Mutex class
326 * ===========================================================================
327 */
328
Mathias Agopian15554362009-07-12 23:11:20 -0700329#if defined(HAVE_PTHREADS)
330// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800331#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800332
333Mutex::Mutex()
334{
335 HANDLE hMutex;
336
337 assert(sizeof(hMutex) == sizeof(mState));
338
339 hMutex = CreateMutex(NULL, FALSE, NULL);
340 mState = (void*) hMutex;
341}
342
343Mutex::Mutex(const char* name)
344{
345 // XXX: name not used for now
346 HANDLE hMutex;
347
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200348 assert(sizeof(hMutex) == sizeof(mState));
349
350 hMutex = CreateMutex(NULL, FALSE, NULL);
351 mState = (void*) hMutex;
352}
353
354Mutex::Mutex(int type, const char* name)
355{
356 // XXX: type and name not used for now
357 HANDLE hMutex;
358
359 assert(sizeof(hMutex) == sizeof(mState));
360
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800361 hMutex = CreateMutex(NULL, FALSE, NULL);
362 mState = (void*) hMutex;
363}
364
365Mutex::~Mutex()
366{
367 CloseHandle((HANDLE) mState);
368}
369
370status_t Mutex::lock()
371{
372 DWORD dwWaitResult;
373 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
374 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
375}
376
377void Mutex::unlock()
378{
379 if (!ReleaseMutex((HANDLE) mState))
380 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
381}
382
383status_t Mutex::tryLock()
384{
385 DWORD dwWaitResult;
386
387 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
388 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
389 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
390 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
391}
392
393#else
394#error "Somebody forgot to implement threads for this platform."
395#endif
396
397
398/*
399 * ===========================================================================
400 * Condition class
401 * ===========================================================================
402 */
403
Mathias Agopian15554362009-07-12 23:11:20 -0700404#if defined(HAVE_PTHREADS)
405// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800406#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800407
408/*
409 * Windows doesn't have a condition variable solution. It's possible
410 * to create one, but it's easy to get it wrong. For a discussion, and
411 * the origin of this implementation, see:
412 *
413 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
414 *
415 * The implementation shown on the page does NOT follow POSIX semantics.
416 * As an optimization they require acquiring the external mutex before
417 * calling signal() and broadcast(), whereas POSIX only requires grabbing
418 * it before calling wait(). The implementation here has been un-optimized
419 * to have the correct behavior.
420 */
421typedef struct WinCondition {
422 // Number of waiting threads.
423 int waitersCount;
424
425 // Serialize access to waitersCount.
426 CRITICAL_SECTION waitersCountLock;
427
428 // Semaphore used to queue up threads waiting for the condition to
429 // become signaled.
430 HANDLE sema;
431
432 // An auto-reset event used by the broadcast/signal thread to wait
433 // for all the waiting thread(s) to wake up and be released from
434 // the semaphore.
435 HANDLE waitersDone;
436
437 // This mutex wouldn't be necessary if we required that the caller
438 // lock the external mutex before calling signal() and broadcast().
439 // I'm trying to mimic pthread semantics though.
440 HANDLE internalMutex;
441
442 // Keeps track of whether we were broadcasting or signaling. This
443 // allows us to optimize the code if we're just signaling.
444 bool wasBroadcast;
445
446 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
447 {
448 // Increment the wait count, avoiding race conditions.
449 EnterCriticalSection(&condState->waitersCountLock);
450 condState->waitersCount++;
451 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
452 // condState->waitersCount, getThreadId());
453 LeaveCriticalSection(&condState->waitersCountLock);
454
455 DWORD timeout = INFINITE;
456 if (abstime) {
457 nsecs_t reltime = *abstime - systemTime();
458 if (reltime < 0)
459 reltime = 0;
460 timeout = reltime/1000000;
461 }
462
463 // Atomically release the external mutex and wait on the semaphore.
464 DWORD res =
465 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
466
467 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
468
469 // Reacquire lock to avoid race conditions.
470 EnterCriticalSection(&condState->waitersCountLock);
471
472 // No longer waiting.
473 condState->waitersCount--;
474
475 // Check to see if we're the last waiter after a broadcast.
476 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
477
478 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
479 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
480
481 LeaveCriticalSection(&condState->waitersCountLock);
482
483 // If we're the last waiter thread during this particular broadcast
484 // then signal broadcast() that we're all awake. It'll drop the
485 // internal mutex.
486 if (lastWaiter) {
487 // Atomically signal the "waitersDone" event and wait until we
488 // can acquire the internal mutex. We want to do this in one step
489 // because it ensures that everybody is in the mutex FIFO before
490 // any thread has a chance to run. Without it, another thread
491 // could wake up, do work, and hop back in ahead of us.
492 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
493 INFINITE, FALSE);
494 } else {
495 // Grab the internal mutex.
496 WaitForSingleObject(condState->internalMutex, INFINITE);
497 }
498
499 // Release the internal and grab the external.
500 ReleaseMutex(condState->internalMutex);
501 WaitForSingleObject(hMutex, INFINITE);
502
503 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
504 }
505} WinCondition;
506
507/*
508 * Constructor. Set up the WinCondition stuff.
509 */
510Condition::Condition()
511{
512 WinCondition* condState = new WinCondition;
513
514 condState->waitersCount = 0;
515 condState->wasBroadcast = false;
516 // semaphore: no security, initial value of 0
517 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
518 InitializeCriticalSection(&condState->waitersCountLock);
519 // auto-reset event, not signaled initially
520 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
521 // used so we don't have to lock external mutex on signal/broadcast
522 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
523
524 mState = condState;
525}
526
527/*
528 * Destructor. Free Windows resources as well as our allocated storage.
529 */
530Condition::~Condition()
531{
532 WinCondition* condState = (WinCondition*) mState;
533 if (condState != NULL) {
534 CloseHandle(condState->sema);
535 CloseHandle(condState->waitersDone);
536 delete condState;
537 }
538}
539
540
541status_t Condition::wait(Mutex& mutex)
542{
543 WinCondition* condState = (WinCondition*) mState;
544 HANDLE hMutex = (HANDLE) mutex.mState;
545
546 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
547}
548
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800549status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
550{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200551 WinCondition* condState = (WinCondition*) mState;
552 HANDLE hMutex = (HANDLE) mutex.mState;
553 nsecs_t absTime = systemTime()+reltime;
554
555 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800556}
557
558/*
559 * Signal the condition variable, allowing one thread to continue.
560 */
561void Condition::signal()
562{
563 WinCondition* condState = (WinCondition*) mState;
564
565 // Lock the internal mutex. This ensures that we don't clash with
566 // broadcast().
567 WaitForSingleObject(condState->internalMutex, INFINITE);
568
569 EnterCriticalSection(&condState->waitersCountLock);
570 bool haveWaiters = (condState->waitersCount > 0);
571 LeaveCriticalSection(&condState->waitersCountLock);
572
573 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
574 // down a notch.
575 if (haveWaiters)
576 ReleaseSemaphore(condState->sema, 1, 0);
577
578 // Release internal mutex.
579 ReleaseMutex(condState->internalMutex);
580}
581
582/*
583 * Signal the condition variable, allowing all threads to continue.
584 *
585 * First we have to wake up all threads waiting on the semaphore, then
586 * we wait until all of the threads have actually been woken before
587 * releasing the internal mutex. This ensures that all threads are woken.
588 */
589void Condition::broadcast()
590{
591 WinCondition* condState = (WinCondition*) mState;
592
593 // Lock the internal mutex. This keeps the guys we're waking up
594 // from getting too far.
595 WaitForSingleObject(condState->internalMutex, INFINITE);
596
597 EnterCriticalSection(&condState->waitersCountLock);
598 bool haveWaiters = false;
599
600 if (condState->waitersCount > 0) {
601 haveWaiters = true;
602 condState->wasBroadcast = true;
603 }
604
605 if (haveWaiters) {
606 // Wake up all the waiters.
607 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
608
609 LeaveCriticalSection(&condState->waitersCountLock);
610
611 // Wait for all awakened threads to acquire the counting semaphore.
612 // The last guy who was waiting sets this.
613 WaitForSingleObject(condState->waitersDone, INFINITE);
614
615 // Reset wasBroadcast. (No crit section needed because nobody
616 // else can wake up to poke at it.)
617 condState->wasBroadcast = 0;
618 } else {
619 // nothing to do
620 LeaveCriticalSection(&condState->waitersCountLock);
621 }
622
623 // Release internal mutex.
624 ReleaseMutex(condState->internalMutex);
625}
626
627#else
628#error "condition variables not supported on this platform"
629#endif
630
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800631// ----------------------------------------------------------------------------
632
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800633/*
634 * This is our thread object!
635 */
636
637Thread::Thread(bool canCallJava)
638 : mCanCallJava(canCallJava),
639 mThread(thread_id_t(-1)),
640 mLock("Thread::mLock"),
641 mStatus(NO_ERROR),
642 mExitPending(false), mRunning(false)
643{
644}
645
646Thread::~Thread()
647{
648}
649
650status_t Thread::readyToRun()
651{
652 return NO_ERROR;
653}
654
655status_t Thread::run(const char* name, int32_t priority, size_t stack)
656{
657 Mutex::Autolock _l(mLock);
658
659 if (mRunning) {
660 // thread already started
661 return INVALID_OPERATION;
662 }
663
664 // reset status and exitPending to their default value, so we can
665 // try again after an error happened (either below, or in readyToRun())
666 mStatus = NO_ERROR;
667 mExitPending = false;
668 mThread = thread_id_t(-1);
669
670 // hold a strong reference on ourself
671 mHoldSelf = this;
672
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800673 mRunning = true;
674
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800675 bool res;
676 if (mCanCallJava) {
677 res = createThreadEtc(_threadLoop,
678 this, name, priority, stack, &mThread);
679 } else {
680 res = androidCreateRawThreadEtc(_threadLoop,
681 this, name, priority, stack, &mThread);
682 }
683
684 if (res == false) {
685 mStatus = UNKNOWN_ERROR; // something happened!
686 mRunning = false;
687 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800688 mHoldSelf.clear(); // "this" may have gone away after this.
689
690 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800691 }
692
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800693 // Do not refer to mStatus here: The thread is already running (may, in fact
694 // already have exited with a valid mStatus result). The NO_ERROR indication
695 // here merely indicates successfully starting the thread and does not
696 // imply successful termination/execution.
697 return NO_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800698}
699
700int Thread::_threadLoop(void* user)
701{
702 Thread* const self = static_cast<Thread*>(user);
703 sp<Thread> strong(self->mHoldSelf);
704 wp<Thread> weak(strong);
705 self->mHoldSelf.clear();
706
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700707#if HAVE_ANDROID_OS
708 // this is very useful for debugging with gdb
709 self->mTid = gettid();
710#endif
711
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800712 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800713
714 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800715 bool result;
716 if (first) {
717 first = false;
718 self->mStatus = self->readyToRun();
719 result = (self->mStatus == NO_ERROR);
720
721 if (result && !self->mExitPending) {
722 // Binder threads (and maybe others) rely on threadLoop
723 // running at least once after a successful ::readyToRun()
724 // (unless, of course, the thread has already been asked to exit
725 // at that point).
726 // This is because threads are essentially used like this:
727 // (new ThreadSubclass())->run();
728 // The caller therefore does not retain a strong reference to
729 // the thread and the thread would simply disappear after the
730 // successful ::readyToRun() call instead of entering the
731 // threadLoop at least once.
732 result = self->threadLoop();
733 }
734 } else {
735 result = self->threadLoop();
736 }
737
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800738 if (result == false || self->mExitPending) {
739 self->mExitPending = true;
740 self->mLock.lock();
741 self->mRunning = false;
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700742 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800743 self->mLock.unlock();
744 break;
745 }
746
747 // Release our strong reference, to let a chance to the thread
748 // to die a peaceful death.
749 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700750 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800751 strong = weak.promote();
752 } while(strong != 0);
753
754 return 0;
755}
756
757void Thread::requestExit()
758{
759 mExitPending = true;
760}
761
762status_t Thread::requestExitAndWait()
763{
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800764 if (mThread == getThreadId()) {
765 LOGW(
766 "Thread (this=%p): don't call waitForExit() from this "
767 "Thread object's thread. It's a guaranteed deadlock!",
768 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800769
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800770 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800771 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800772
773 requestExit();
774
775 Mutex::Autolock _l(mLock);
776 while (mRunning == true) {
777 mThreadExitedCondition.wait(mLock);
778 }
779 mExitPending = false;
780
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800781 return mStatus;
782}
783
784bool Thread::exitPending() const
785{
786 return mExitPending;
787}
788
789
790
791}; // namespace android