blob: e5ece8e8a25a6c3c8d66fce2564f43bf5253d2b3 [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 Hackborn193c18c2010-09-07 12:32:19 -0700284#if defined(HAVE_PTHREADS)
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700285static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
286static bool gDoSchedulingGroup = true;
287
288static void checkDoSchedulingGroup(void) {
289 char buf[PROPERTY_VALUE_MAX];
290 int len = property_get("debug.sys.noschedgroups", buf, "");
291 if (len > 0) {
292 int temp;
293 if (sscanf(buf, "%d", &temp) == 1) {
294 gDoSchedulingGroup = temp == 0;
295 }
296 }
297}
Dianne Hackborn193c18c2010-09-07 12:32:19 -0700298#endif
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700299
Dianne Hackborn235af972009-12-07 17:59:37 -0800300int androidSetThreadSchedulingGroup(pid_t tid, int grp)
301{
302 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
303 return BAD_VALUE;
304 }
305
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800306#if defined(HAVE_PTHREADS)
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700307 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
308 if (gDoSchedulingGroup) {
309 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
310 SP_BACKGROUND : SP_FOREGROUND)) {
311 return PERMISSION_DENIED;
312 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800313 }
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800314#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800315
316 return NO_ERROR;
317}
318
319int androidSetThreadPriority(pid_t tid, int pri)
320{
321 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800322
323#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800324 int lasterr = 0;
325
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700326 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
327 if (gDoSchedulingGroup) {
328 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
329 rc = set_sched_policy(tid, SP_BACKGROUND);
330 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
331 rc = set_sched_policy(tid, SP_FOREGROUND);
332 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800333 }
334
335 if (rc) {
336 lasterr = errno;
337 }
338
339 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
340 rc = INVALID_OPERATION;
341 } else {
342 errno = lasterr;
343 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800344#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800345
346 return rc;
347}
348
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800349namespace android {
350
351/*
352 * ===========================================================================
353 * Mutex class
354 * ===========================================================================
355 */
356
Mathias Agopian15554362009-07-12 23:11:20 -0700357#if defined(HAVE_PTHREADS)
358// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800359#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800360
361Mutex::Mutex()
362{
363 HANDLE hMutex;
364
365 assert(sizeof(hMutex) == sizeof(mState));
366
367 hMutex = CreateMutex(NULL, FALSE, NULL);
368 mState = (void*) hMutex;
369}
370
371Mutex::Mutex(const char* name)
372{
373 // XXX: name not used for now
374 HANDLE hMutex;
375
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200376 assert(sizeof(hMutex) == sizeof(mState));
377
378 hMutex = CreateMutex(NULL, FALSE, NULL);
379 mState = (void*) hMutex;
380}
381
382Mutex::Mutex(int type, const char* name)
383{
384 // XXX: type and name not used for now
385 HANDLE hMutex;
386
387 assert(sizeof(hMutex) == sizeof(mState));
388
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800389 hMutex = CreateMutex(NULL, FALSE, NULL);
390 mState = (void*) hMutex;
391}
392
393Mutex::~Mutex()
394{
395 CloseHandle((HANDLE) mState);
396}
397
398status_t Mutex::lock()
399{
400 DWORD dwWaitResult;
401 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
402 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
403}
404
405void Mutex::unlock()
406{
407 if (!ReleaseMutex((HANDLE) mState))
408 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
409}
410
411status_t Mutex::tryLock()
412{
413 DWORD dwWaitResult;
414
415 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
416 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
417 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
418 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
419}
420
421#else
422#error "Somebody forgot to implement threads for this platform."
423#endif
424
425
426/*
427 * ===========================================================================
428 * Condition class
429 * ===========================================================================
430 */
431
Mathias Agopian15554362009-07-12 23:11:20 -0700432#if defined(HAVE_PTHREADS)
433// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800434#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800435
436/*
437 * Windows doesn't have a condition variable solution. It's possible
438 * to create one, but it's easy to get it wrong. For a discussion, and
439 * the origin of this implementation, see:
440 *
441 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
442 *
443 * The implementation shown on the page does NOT follow POSIX semantics.
444 * As an optimization they require acquiring the external mutex before
445 * calling signal() and broadcast(), whereas POSIX only requires grabbing
446 * it before calling wait(). The implementation here has been un-optimized
447 * to have the correct behavior.
448 */
449typedef struct WinCondition {
450 // Number of waiting threads.
451 int waitersCount;
452
453 // Serialize access to waitersCount.
454 CRITICAL_SECTION waitersCountLock;
455
456 // Semaphore used to queue up threads waiting for the condition to
457 // become signaled.
458 HANDLE sema;
459
460 // An auto-reset event used by the broadcast/signal thread to wait
461 // for all the waiting thread(s) to wake up and be released from
462 // the semaphore.
463 HANDLE waitersDone;
464
465 // This mutex wouldn't be necessary if we required that the caller
466 // lock the external mutex before calling signal() and broadcast().
467 // I'm trying to mimic pthread semantics though.
468 HANDLE internalMutex;
469
470 // Keeps track of whether we were broadcasting or signaling. This
471 // allows us to optimize the code if we're just signaling.
472 bool wasBroadcast;
473
474 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
475 {
476 // Increment the wait count, avoiding race conditions.
477 EnterCriticalSection(&condState->waitersCountLock);
478 condState->waitersCount++;
479 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
480 // condState->waitersCount, getThreadId());
481 LeaveCriticalSection(&condState->waitersCountLock);
482
483 DWORD timeout = INFINITE;
484 if (abstime) {
485 nsecs_t reltime = *abstime - systemTime();
486 if (reltime < 0)
487 reltime = 0;
488 timeout = reltime/1000000;
489 }
490
491 // Atomically release the external mutex and wait on the semaphore.
492 DWORD res =
493 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
494
495 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
496
497 // Reacquire lock to avoid race conditions.
498 EnterCriticalSection(&condState->waitersCountLock);
499
500 // No longer waiting.
501 condState->waitersCount--;
502
503 // Check to see if we're the last waiter after a broadcast.
504 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
505
506 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
507 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
508
509 LeaveCriticalSection(&condState->waitersCountLock);
510
511 // If we're the last waiter thread during this particular broadcast
512 // then signal broadcast() that we're all awake. It'll drop the
513 // internal mutex.
514 if (lastWaiter) {
515 // Atomically signal the "waitersDone" event and wait until we
516 // can acquire the internal mutex. We want to do this in one step
517 // because it ensures that everybody is in the mutex FIFO before
518 // any thread has a chance to run. Without it, another thread
519 // could wake up, do work, and hop back in ahead of us.
520 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
521 INFINITE, FALSE);
522 } else {
523 // Grab the internal mutex.
524 WaitForSingleObject(condState->internalMutex, INFINITE);
525 }
526
527 // Release the internal and grab the external.
528 ReleaseMutex(condState->internalMutex);
529 WaitForSingleObject(hMutex, INFINITE);
530
531 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
532 }
533} WinCondition;
534
535/*
536 * Constructor. Set up the WinCondition stuff.
537 */
538Condition::Condition()
539{
540 WinCondition* condState = new WinCondition;
541
542 condState->waitersCount = 0;
543 condState->wasBroadcast = false;
544 // semaphore: no security, initial value of 0
545 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
546 InitializeCriticalSection(&condState->waitersCountLock);
547 // auto-reset event, not signaled initially
548 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
549 // used so we don't have to lock external mutex on signal/broadcast
550 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
551
552 mState = condState;
553}
554
555/*
556 * Destructor. Free Windows resources as well as our allocated storage.
557 */
558Condition::~Condition()
559{
560 WinCondition* condState = (WinCondition*) mState;
561 if (condState != NULL) {
562 CloseHandle(condState->sema);
563 CloseHandle(condState->waitersDone);
564 delete condState;
565 }
566}
567
568
569status_t Condition::wait(Mutex& mutex)
570{
571 WinCondition* condState = (WinCondition*) mState;
572 HANDLE hMutex = (HANDLE) mutex.mState;
573
574 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
575}
576
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800577status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
578{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200579 WinCondition* condState = (WinCondition*) mState;
580 HANDLE hMutex = (HANDLE) mutex.mState;
581 nsecs_t absTime = systemTime()+reltime;
582
583 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800584}
585
586/*
587 * Signal the condition variable, allowing one thread to continue.
588 */
589void Condition::signal()
590{
591 WinCondition* condState = (WinCondition*) mState;
592
593 // Lock the internal mutex. This ensures that we don't clash with
594 // broadcast().
595 WaitForSingleObject(condState->internalMutex, INFINITE);
596
597 EnterCriticalSection(&condState->waitersCountLock);
598 bool haveWaiters = (condState->waitersCount > 0);
599 LeaveCriticalSection(&condState->waitersCountLock);
600
601 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
602 // down a notch.
603 if (haveWaiters)
604 ReleaseSemaphore(condState->sema, 1, 0);
605
606 // Release internal mutex.
607 ReleaseMutex(condState->internalMutex);
608}
609
610/*
611 * Signal the condition variable, allowing all threads to continue.
612 *
613 * First we have to wake up all threads waiting on the semaphore, then
614 * we wait until all of the threads have actually been woken before
615 * releasing the internal mutex. This ensures that all threads are woken.
616 */
617void Condition::broadcast()
618{
619 WinCondition* condState = (WinCondition*) mState;
620
621 // Lock the internal mutex. This keeps the guys we're waking up
622 // from getting too far.
623 WaitForSingleObject(condState->internalMutex, INFINITE);
624
625 EnterCriticalSection(&condState->waitersCountLock);
626 bool haveWaiters = false;
627
628 if (condState->waitersCount > 0) {
629 haveWaiters = true;
630 condState->wasBroadcast = true;
631 }
632
633 if (haveWaiters) {
634 // Wake up all the waiters.
635 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
636
637 LeaveCriticalSection(&condState->waitersCountLock);
638
639 // Wait for all awakened threads to acquire the counting semaphore.
640 // The last guy who was waiting sets this.
641 WaitForSingleObject(condState->waitersDone, INFINITE);
642
643 // Reset wasBroadcast. (No crit section needed because nobody
644 // else can wake up to poke at it.)
645 condState->wasBroadcast = 0;
646 } else {
647 // nothing to do
648 LeaveCriticalSection(&condState->waitersCountLock);
649 }
650
651 // Release internal mutex.
652 ReleaseMutex(condState->internalMutex);
653}
654
655#else
656#error "condition variables not supported on this platform"
657#endif
658
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800659// ----------------------------------------------------------------------------
660
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800661/*
662 * This is our thread object!
663 */
664
665Thread::Thread(bool canCallJava)
666 : mCanCallJava(canCallJava),
667 mThread(thread_id_t(-1)),
668 mLock("Thread::mLock"),
669 mStatus(NO_ERROR),
670 mExitPending(false), mRunning(false)
671{
672}
673
674Thread::~Thread()
675{
676}
677
678status_t Thread::readyToRun()
679{
680 return NO_ERROR;
681}
682
683status_t Thread::run(const char* name, int32_t priority, size_t stack)
684{
685 Mutex::Autolock _l(mLock);
686
687 if (mRunning) {
688 // thread already started
689 return INVALID_OPERATION;
690 }
691
692 // reset status and exitPending to their default value, so we can
693 // try again after an error happened (either below, or in readyToRun())
694 mStatus = NO_ERROR;
695 mExitPending = false;
696 mThread = thread_id_t(-1);
697
698 // hold a strong reference on ourself
699 mHoldSelf = this;
700
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800701 mRunning = true;
702
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800703 bool res;
704 if (mCanCallJava) {
705 res = createThreadEtc(_threadLoop,
706 this, name, priority, stack, &mThread);
707 } else {
708 res = androidCreateRawThreadEtc(_threadLoop,
709 this, name, priority, stack, &mThread);
710 }
711
712 if (res == false) {
713 mStatus = UNKNOWN_ERROR; // something happened!
714 mRunning = false;
715 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800716 mHoldSelf.clear(); // "this" may have gone away after this.
717
718 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800719 }
720
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800721 // Do not refer to mStatus here: The thread is already running (may, in fact
722 // already have exited with a valid mStatus result). The NO_ERROR indication
723 // here merely indicates successfully starting the thread and does not
724 // imply successful termination/execution.
725 return NO_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800726}
727
728int Thread::_threadLoop(void* user)
729{
730 Thread* const self = static_cast<Thread*>(user);
731 sp<Thread> strong(self->mHoldSelf);
732 wp<Thread> weak(strong);
733 self->mHoldSelf.clear();
734
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700735#if HAVE_ANDROID_OS
736 // this is very useful for debugging with gdb
737 self->mTid = gettid();
738#endif
739
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800740 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800741
742 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800743 bool result;
744 if (first) {
745 first = false;
746 self->mStatus = self->readyToRun();
747 result = (self->mStatus == NO_ERROR);
748
749 if (result && !self->mExitPending) {
750 // Binder threads (and maybe others) rely on threadLoop
751 // running at least once after a successful ::readyToRun()
752 // (unless, of course, the thread has already been asked to exit
753 // at that point).
754 // This is because threads are essentially used like this:
755 // (new ThreadSubclass())->run();
756 // The caller therefore does not retain a strong reference to
757 // the thread and the thread would simply disappear after the
758 // successful ::readyToRun() call instead of entering the
759 // threadLoop at least once.
760 result = self->threadLoop();
761 }
762 } else {
763 result = self->threadLoop();
764 }
765
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800766 if (result == false || self->mExitPending) {
767 self->mExitPending = true;
768 self->mLock.lock();
769 self->mRunning = false;
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700770 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800771 self->mLock.unlock();
772 break;
773 }
774
775 // Release our strong reference, to let a chance to the thread
776 // to die a peaceful death.
777 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700778 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800779 strong = weak.promote();
780 } while(strong != 0);
781
782 return 0;
783}
784
785void Thread::requestExit()
786{
787 mExitPending = true;
788}
789
790status_t Thread::requestExitAndWait()
791{
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800792 if (mThread == getThreadId()) {
793 LOGW(
794 "Thread (this=%p): don't call waitForExit() from this "
795 "Thread object's thread. It's a guaranteed deadlock!",
796 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800797
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800798 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800799 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800800
801 requestExit();
802
803 Mutex::Autolock _l(mLock);
804 while (mRunning == true) {
805 mThreadExitedCondition.wait(mLock);
806 }
807 mExitPending = false;
808
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800809 return mStatus;
810}
811
812bool Thread::exitPending() const
813{
814 return mExitPending;
815}
816
817
818
819}; // namespace android