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