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