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