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