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