blob: c8de1f51ed8a22bdac1913493e34009ec5efa8dc [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>
Dianne Hackborn16d217e2010-09-03 17:07:07 -070024#include <cutils/properties.h>
Dianne Hackborn235af972009-12-07 17:59:37 -080025
The Android Open Source Projectcbb10112009-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 Projectcbb10112009-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 Projectcbb10112009-03-03 19:31:44 -080058// ----------------------------------------------------------------------------
59
60/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070061 * Create and run a new thread.
The Android Open Source Projectcbb10112009-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
68struct thread_data_t {
69 thread_func_t entryFunction;
70 void* userData;
71 int priority;
72 char * threadName;
73
74 // we use this trampoline when we need to set the priority with
75 // nice/setpriority.
76 static int trampoline(const thread_data_t* t) {
77 thread_func_t f = t->entryFunction;
78 void* u = t->userData;
79 int prio = t->priority;
80 char * name = t->threadName;
81 delete t;
82 setpriority(PRIO_PROCESS, 0, prio);
83 if (name) {
84#if defined(HAVE_PRCTL)
85 // Mac OS doesn't have this, and we build libutil for the host too
86 int hasAt = 0;
87 int hasDot = 0;
88 char *s = name;
89 while (*s) {
90 if (*s == '.') hasDot = 1;
91 else if (*s == '@') hasAt = 1;
92 s++;
93 }
94 int len = s - name;
95 if (len < 15 || hasAt || !hasDot) {
96 s = name;
97 } else {
98 s = name + len - 15;
99 }
100 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
101#endif
102 free(name);
103 }
104 return f(u);
105 }
106};
107
108int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
109 void *userData,
110 const char* threadName,
111 int32_t threadPriority,
112 size_t threadStackSize,
113 android_thread_id_t *threadId)
114{
115 pthread_attr_t attr;
116 pthread_attr_init(&attr);
117 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
118
119#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
120 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
121 // We could avoid the trampoline if there was a way to get to the
122 // android_thread_id_t (pid) from pthread_t
123 thread_data_t* t = new thread_data_t;
124 t->priority = threadPriority;
125 t->threadName = threadName ? strdup(threadName) : NULL;
126 t->entryFunction = entryFunction;
127 t->userData = userData;
128 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
129 userData = t;
130 }
131#endif
132
133 if (threadStackSize) {
134 pthread_attr_setstacksize(&attr, threadStackSize);
135 }
136
137 errno = 0;
138 pthread_t thread;
139 int result = pthread_create(&thread, &attr,
140 (android_pthread_entry)entryFunction, userData);
141 if (result != 0) {
142 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
143 "(android threadPriority=%d)",
144 entryFunction, result, errno, threadPriority);
145 return 0;
146 }
147
148 if (threadId != NULL) {
149 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
150 }
151 return 1;
152}
153
154android_thread_id_t androidGetThreadId()
155{
156 return (android_thread_id_t)pthread_self();
157}
158
159// ----------------------------------------------------------------------------
160#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800161// ----------------------------------------------------------------------------
162
163/*
164 * Trampoline to make us __stdcall-compliant.
165 *
166 * We're expected to delete "vDetails" when we're done.
167 */
168struct threadDetails {
169 int (*func)(void*);
170 void* arg;
171};
172static __stdcall unsigned int threadIntermediary(void* vDetails)
173{
174 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
175 int result;
176
177 result = (*(pDetails->func))(pDetails->arg);
178
179 delete pDetails;
180
181 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
182 return (unsigned int) result;
183}
184
185/*
186 * Create and run a new thread.
187 */
188static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
189{
190 HANDLE hThread;
191 struct threadDetails* pDetails = new threadDetails; // must be on heap
192 unsigned int thrdaddr;
193
194 pDetails->func = fn;
195 pDetails->arg = arg;
196
197#if defined(HAVE__BEGINTHREADEX)
198 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
199 &thrdaddr);
200 if (hThread == 0)
201#elif defined(HAVE_CREATETHREAD)
202 hThread = CreateThread(NULL, 0,
203 (LPTHREAD_START_ROUTINE) threadIntermediary,
204 (void*) pDetails, 0, (DWORD*) &thrdaddr);
205 if (hThread == NULL)
206#endif
207 {
208 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
209 return false;
210 }
211
212#if defined(HAVE_CREATETHREAD)
213 /* close the management handle */
214 CloseHandle(hThread);
215#endif
216
217 if (id != NULL) {
218 *id = (android_thread_id_t)thrdaddr;
219 }
220
221 return true;
222}
223
224int androidCreateRawThreadEtc(android_thread_func_t fn,
225 void *userData,
226 const char* threadName,
227 int32_t threadPriority,
228 size_t threadStackSize,
229 android_thread_id_t *threadId)
230{
231 return doCreateThread( fn, userData, threadId);
232}
233
234android_thread_id_t androidGetThreadId()
235{
236 return (android_thread_id_t)GetCurrentThreadId();
237}
238
239// ----------------------------------------------------------------------------
240#else
241#error "Threads not supported"
242#endif
243
244// ----------------------------------------------------------------------------
245
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800246int androidCreateThread(android_thread_func_t fn, void* arg)
247{
248 return createThreadEtc(fn, arg);
249}
250
251int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
252{
253 return createThreadEtc(fn, arg, "android:unnamed_thread",
254 PRIORITY_DEFAULT, 0, id);
255}
256
257static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
258
259int androidCreateThreadEtc(android_thread_func_t entryFunction,
260 void *userData,
261 const char* threadName,
262 int32_t threadPriority,
263 size_t threadStackSize,
264 android_thread_id_t *threadId)
265{
266 return gCreateThreadFn(entryFunction, userData, threadName,
267 threadPriority, threadStackSize, threadId);
268}
269
270void androidSetCreateThreadFunc(android_create_thread_fn func)
271{
272 gCreateThreadFn = func;
273}
274
Dianne Hackborn235af972009-12-07 17:59:37 -0800275pid_t androidGetTid()
276{
277#ifdef HAVE_GETTID
278 return gettid();
279#else
280 return getpid();
281#endif
282}
283
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700284static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
285static bool gDoSchedulingGroup = true;
286
287static void checkDoSchedulingGroup(void) {
288 char buf[PROPERTY_VALUE_MAX];
289 int len = property_get("debug.sys.noschedgroups", buf, "");
290 if (len > 0) {
291 int temp;
292 if (sscanf(buf, "%d", &temp) == 1) {
293 gDoSchedulingGroup = temp == 0;
294 }
295 }
296}
297
Dianne Hackborn235af972009-12-07 17:59:37 -0800298int androidSetThreadSchedulingGroup(pid_t tid, int grp)
299{
300 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
301 return BAD_VALUE;
302 }
303
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800304#if defined(HAVE_PTHREADS)
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700305 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
306 if (gDoSchedulingGroup) {
307 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
308 SP_BACKGROUND : SP_FOREGROUND)) {
309 return PERMISSION_DENIED;
310 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800311 }
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800312#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800313
314 return NO_ERROR;
315}
316
317int androidSetThreadPriority(pid_t tid, int pri)
318{
319 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800320
321#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800322 int lasterr = 0;
323
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700324 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
325 if (gDoSchedulingGroup) {
326 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
327 rc = set_sched_policy(tid, SP_BACKGROUND);
328 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
329 rc = set_sched_policy(tid, SP_FOREGROUND);
330 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800331 }
332
333 if (rc) {
334 lasterr = errno;
335 }
336
337 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
338 rc = INVALID_OPERATION;
339 } else {
340 errno = lasterr;
341 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800342#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800343
344 return rc;
345}
346
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800347namespace android {
348
349/*
350 * ===========================================================================
351 * Mutex class
352 * ===========================================================================
353 */
354
Mathias Agopian15554362009-07-12 23:11:20 -0700355#if defined(HAVE_PTHREADS)
356// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800357#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800358
359Mutex::Mutex()
360{
361 HANDLE hMutex;
362
363 assert(sizeof(hMutex) == sizeof(mState));
364
365 hMutex = CreateMutex(NULL, FALSE, NULL);
366 mState = (void*) hMutex;
367}
368
369Mutex::Mutex(const char* name)
370{
371 // XXX: name not used for now
372 HANDLE hMutex;
373
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200374 assert(sizeof(hMutex) == sizeof(mState));
375
376 hMutex = CreateMutex(NULL, FALSE, NULL);
377 mState = (void*) hMutex;
378}
379
380Mutex::Mutex(int type, const char* name)
381{
382 // XXX: type and name not used for now
383 HANDLE hMutex;
384
385 assert(sizeof(hMutex) == sizeof(mState));
386
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800387 hMutex = CreateMutex(NULL, FALSE, NULL);
388 mState = (void*) hMutex;
389}
390
391Mutex::~Mutex()
392{
393 CloseHandle((HANDLE) mState);
394}
395
396status_t Mutex::lock()
397{
398 DWORD dwWaitResult;
399 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
400 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
401}
402
403void Mutex::unlock()
404{
405 if (!ReleaseMutex((HANDLE) mState))
406 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
407}
408
409status_t Mutex::tryLock()
410{
411 DWORD dwWaitResult;
412
413 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
414 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
415 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
416 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
417}
418
419#else
420#error "Somebody forgot to implement threads for this platform."
421#endif
422
423
424/*
425 * ===========================================================================
426 * Condition class
427 * ===========================================================================
428 */
429
Mathias Agopian15554362009-07-12 23:11:20 -0700430#if defined(HAVE_PTHREADS)
431// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800432#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800433
434/*
435 * Windows doesn't have a condition variable solution. It's possible
436 * to create one, but it's easy to get it wrong. For a discussion, and
437 * the origin of this implementation, see:
438 *
439 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
440 *
441 * The implementation shown on the page does NOT follow POSIX semantics.
442 * As an optimization they require acquiring the external mutex before
443 * calling signal() and broadcast(), whereas POSIX only requires grabbing
444 * it before calling wait(). The implementation here has been un-optimized
445 * to have the correct behavior.
446 */
447typedef struct WinCondition {
448 // Number of waiting threads.
449 int waitersCount;
450
451 // Serialize access to waitersCount.
452 CRITICAL_SECTION waitersCountLock;
453
454 // Semaphore used to queue up threads waiting for the condition to
455 // become signaled.
456 HANDLE sema;
457
458 // An auto-reset event used by the broadcast/signal thread to wait
459 // for all the waiting thread(s) to wake up and be released from
460 // the semaphore.
461 HANDLE waitersDone;
462
463 // This mutex wouldn't be necessary if we required that the caller
464 // lock the external mutex before calling signal() and broadcast().
465 // I'm trying to mimic pthread semantics though.
466 HANDLE internalMutex;
467
468 // Keeps track of whether we were broadcasting or signaling. This
469 // allows us to optimize the code if we're just signaling.
470 bool wasBroadcast;
471
472 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
473 {
474 // Increment the wait count, avoiding race conditions.
475 EnterCriticalSection(&condState->waitersCountLock);
476 condState->waitersCount++;
477 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
478 // condState->waitersCount, getThreadId());
479 LeaveCriticalSection(&condState->waitersCountLock);
480
481 DWORD timeout = INFINITE;
482 if (abstime) {
483 nsecs_t reltime = *abstime - systemTime();
484 if (reltime < 0)
485 reltime = 0;
486 timeout = reltime/1000000;
487 }
488
489 // Atomically release the external mutex and wait on the semaphore.
490 DWORD res =
491 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
492
493 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
494
495 // Reacquire lock to avoid race conditions.
496 EnterCriticalSection(&condState->waitersCountLock);
497
498 // No longer waiting.
499 condState->waitersCount--;
500
501 // Check to see if we're the last waiter after a broadcast.
502 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
503
504 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
505 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
506
507 LeaveCriticalSection(&condState->waitersCountLock);
508
509 // If we're the last waiter thread during this particular broadcast
510 // then signal broadcast() that we're all awake. It'll drop the
511 // internal mutex.
512 if (lastWaiter) {
513 // Atomically signal the "waitersDone" event and wait until we
514 // can acquire the internal mutex. We want to do this in one step
515 // because it ensures that everybody is in the mutex FIFO before
516 // any thread has a chance to run. Without it, another thread
517 // could wake up, do work, and hop back in ahead of us.
518 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
519 INFINITE, FALSE);
520 } else {
521 // Grab the internal mutex.
522 WaitForSingleObject(condState->internalMutex, INFINITE);
523 }
524
525 // Release the internal and grab the external.
526 ReleaseMutex(condState->internalMutex);
527 WaitForSingleObject(hMutex, INFINITE);
528
529 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
530 }
531} WinCondition;
532
533/*
534 * Constructor. Set up the WinCondition stuff.
535 */
536Condition::Condition()
537{
538 WinCondition* condState = new WinCondition;
539
540 condState->waitersCount = 0;
541 condState->wasBroadcast = false;
542 // semaphore: no security, initial value of 0
543 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
544 InitializeCriticalSection(&condState->waitersCountLock);
545 // auto-reset event, not signaled initially
546 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
547 // used so we don't have to lock external mutex on signal/broadcast
548 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
549
550 mState = condState;
551}
552
553/*
554 * Destructor. Free Windows resources as well as our allocated storage.
555 */
556Condition::~Condition()
557{
558 WinCondition* condState = (WinCondition*) mState;
559 if (condState != NULL) {
560 CloseHandle(condState->sema);
561 CloseHandle(condState->waitersDone);
562 delete condState;
563 }
564}
565
566
567status_t Condition::wait(Mutex& mutex)
568{
569 WinCondition* condState = (WinCondition*) mState;
570 HANDLE hMutex = (HANDLE) mutex.mState;
571
572 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
573}
574
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800575status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
576{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200577 WinCondition* condState = (WinCondition*) mState;
578 HANDLE hMutex = (HANDLE) mutex.mState;
579 nsecs_t absTime = systemTime()+reltime;
580
581 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800582}
583
584/*
585 * Signal the condition variable, allowing one thread to continue.
586 */
587void Condition::signal()
588{
589 WinCondition* condState = (WinCondition*) mState;
590
591 // Lock the internal mutex. This ensures that we don't clash with
592 // broadcast().
593 WaitForSingleObject(condState->internalMutex, INFINITE);
594
595 EnterCriticalSection(&condState->waitersCountLock);
596 bool haveWaiters = (condState->waitersCount > 0);
597 LeaveCriticalSection(&condState->waitersCountLock);
598
599 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
600 // down a notch.
601 if (haveWaiters)
602 ReleaseSemaphore(condState->sema, 1, 0);
603
604 // Release internal mutex.
605 ReleaseMutex(condState->internalMutex);
606}
607
608/*
609 * Signal the condition variable, allowing all threads to continue.
610 *
611 * First we have to wake up all threads waiting on the semaphore, then
612 * we wait until all of the threads have actually been woken before
613 * releasing the internal mutex. This ensures that all threads are woken.
614 */
615void Condition::broadcast()
616{
617 WinCondition* condState = (WinCondition*) mState;
618
619 // Lock the internal mutex. This keeps the guys we're waking up
620 // from getting too far.
621 WaitForSingleObject(condState->internalMutex, INFINITE);
622
623 EnterCriticalSection(&condState->waitersCountLock);
624 bool haveWaiters = false;
625
626 if (condState->waitersCount > 0) {
627 haveWaiters = true;
628 condState->wasBroadcast = true;
629 }
630
631 if (haveWaiters) {
632 // Wake up all the waiters.
633 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
634
635 LeaveCriticalSection(&condState->waitersCountLock);
636
637 // Wait for all awakened threads to acquire the counting semaphore.
638 // The last guy who was waiting sets this.
639 WaitForSingleObject(condState->waitersDone, INFINITE);
640
641 // Reset wasBroadcast. (No crit section needed because nobody
642 // else can wake up to poke at it.)
643 condState->wasBroadcast = 0;
644 } else {
645 // nothing to do
646 LeaveCriticalSection(&condState->waitersCountLock);
647 }
648
649 // Release internal mutex.
650 ReleaseMutex(condState->internalMutex);
651}
652
653#else
654#error "condition variables not supported on this platform"
655#endif
656
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800657// ----------------------------------------------------------------------------
658
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800659/*
660 * This is our thread object!
661 */
662
663Thread::Thread(bool canCallJava)
664 : mCanCallJava(canCallJava),
665 mThread(thread_id_t(-1)),
666 mLock("Thread::mLock"),
667 mStatus(NO_ERROR),
668 mExitPending(false), mRunning(false)
669{
670}
671
672Thread::~Thread()
673{
674}
675
676status_t Thread::readyToRun()
677{
678 return NO_ERROR;
679}
680
681status_t Thread::run(const char* name, int32_t priority, size_t stack)
682{
683 Mutex::Autolock _l(mLock);
684
685 if (mRunning) {
686 // thread already started
687 return INVALID_OPERATION;
688 }
689
690 // reset status and exitPending to their default value, so we can
691 // try again after an error happened (either below, or in readyToRun())
692 mStatus = NO_ERROR;
693 mExitPending = false;
694 mThread = thread_id_t(-1);
695
696 // hold a strong reference on ourself
697 mHoldSelf = this;
698
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800699 mRunning = true;
700
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800701 bool res;
702 if (mCanCallJava) {
703 res = createThreadEtc(_threadLoop,
704 this, name, priority, stack, &mThread);
705 } else {
706 res = androidCreateRawThreadEtc(_threadLoop,
707 this, name, priority, stack, &mThread);
708 }
709
710 if (res == false) {
711 mStatus = UNKNOWN_ERROR; // something happened!
712 mRunning = false;
713 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800714 mHoldSelf.clear(); // "this" may have gone away after this.
715
716 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800717 }
718
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800719 // Do not refer to mStatus here: The thread is already running (may, in fact
720 // already have exited with a valid mStatus result). The NO_ERROR indication
721 // here merely indicates successfully starting the thread and does not
722 // imply successful termination/execution.
723 return NO_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800724}
725
726int Thread::_threadLoop(void* user)
727{
728 Thread* const self = static_cast<Thread*>(user);
729 sp<Thread> strong(self->mHoldSelf);
730 wp<Thread> weak(strong);
731 self->mHoldSelf.clear();
732
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700733#if HAVE_ANDROID_OS
734 // this is very useful for debugging with gdb
735 self->mTid = gettid();
736#endif
737
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800738 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800739
740 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800741 bool result;
742 if (first) {
743 first = false;
744 self->mStatus = self->readyToRun();
745 result = (self->mStatus == NO_ERROR);
746
747 if (result && !self->mExitPending) {
748 // Binder threads (and maybe others) rely on threadLoop
749 // running at least once after a successful ::readyToRun()
750 // (unless, of course, the thread has already been asked to exit
751 // at that point).
752 // This is because threads are essentially used like this:
753 // (new ThreadSubclass())->run();
754 // The caller therefore does not retain a strong reference to
755 // the thread and the thread would simply disappear after the
756 // successful ::readyToRun() call instead of entering the
757 // threadLoop at least once.
758 result = self->threadLoop();
759 }
760 } else {
761 result = self->threadLoop();
762 }
763
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800764 if (result == false || self->mExitPending) {
765 self->mExitPending = true;
766 self->mLock.lock();
767 self->mRunning = false;
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700768 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800769 self->mLock.unlock();
770 break;
771 }
772
773 // Release our strong reference, to let a chance to the thread
774 // to die a peaceful death.
775 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700776 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800777 strong = weak.promote();
778 } while(strong != 0);
779
780 return 0;
781}
782
783void Thread::requestExit()
784{
785 mExitPending = true;
786}
787
788status_t Thread::requestExitAndWait()
789{
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800790 if (mThread == getThreadId()) {
791 LOGW(
792 "Thread (this=%p): don't call waitForExit() from this "
793 "Thread object's thread. It's a guaranteed deadlock!",
794 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800795
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800796 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800797 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800798
799 requestExit();
800
801 Mutex::Autolock _l(mLock);
802 while (mRunning == true) {
803 mThreadExitedCondition.wait(mLock);
804 }
805 mExitPending = false;
806
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800807 return mStatus;
808}
809
810bool Thread::exitPending() const
811{
812 return mExitPending;
813}
814
815
816
817}; // namespace android