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