blob: 50312e7bb7d3191ff15922ccfbe492a139c75a0b [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) {
Glenn Kasten5e0243f2011-06-22 17:42:23 -0700319 // set_sched_policy does not support tid == 0
320 if (tid == 0) {
321 tid = androidGetTid();
322 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700323 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
324 SP_BACKGROUND : SP_FOREGROUND)) {
325 return PERMISSION_DENIED;
326 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800327 }
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800328#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800329
330 return NO_ERROR;
331}
332
333int androidSetThreadPriority(pid_t tid, int pri)
334{
335 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800336
337#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800338 int lasterr = 0;
339
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700340 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
341 if (gDoSchedulingGroup) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700342 // 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 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700349 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700350 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700351 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700352 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700353 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800354 }
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 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800365#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800366
367 return rc;
368}
369
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800370namespace android {
371
372/*
373 * ===========================================================================
374 * Mutex class
375 * ===========================================================================
376 */
377
Mathias Agopian15554362009-07-12 23:11:20 -0700378#if defined(HAVE_PTHREADS)
379// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800380#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800381
382Mutex::Mutex()
383{
384 HANDLE hMutex;
385
386 assert(sizeof(hMutex) == sizeof(mState));
387
388 hMutex = CreateMutex(NULL, FALSE, NULL);
389 mState = (void*) hMutex;
390}
391
392Mutex::Mutex(const char* name)
393{
394 // XXX: name not used for now
395 HANDLE hMutex;
396
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200397 assert(sizeof(hMutex) == sizeof(mState));
398
399 hMutex = CreateMutex(NULL, FALSE, NULL);
400 mState = (void*) hMutex;
401}
402
403Mutex::Mutex(int type, const char* name)
404{
405 // XXX: type and name not used for now
406 HANDLE hMutex;
407
408 assert(sizeof(hMutex) == sizeof(mState));
409
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800410 hMutex = CreateMutex(NULL, FALSE, NULL);
411 mState = (void*) hMutex;
412}
413
414Mutex::~Mutex()
415{
416 CloseHandle((HANDLE) mState);
417}
418
419status_t Mutex::lock()
420{
421 DWORD dwWaitResult;
422 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
423 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
424}
425
426void Mutex::unlock()
427{
428 if (!ReleaseMutex((HANDLE) mState))
429 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
430}
431
432status_t Mutex::tryLock()
433{
434 DWORD dwWaitResult;
435
436 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
437 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
438 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
439 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
440}
441
442#else
443#error "Somebody forgot to implement threads for this platform."
444#endif
445
446
447/*
448 * ===========================================================================
449 * Condition class
450 * ===========================================================================
451 */
452
Mathias Agopian15554362009-07-12 23:11:20 -0700453#if defined(HAVE_PTHREADS)
454// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800455#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800456
457/*
458 * Windows doesn't have a condition variable solution. It's possible
459 * to create one, but it's easy to get it wrong. For a discussion, and
460 * the origin of this implementation, see:
461 *
462 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
463 *
464 * The implementation shown on the page does NOT follow POSIX semantics.
465 * As an optimization they require acquiring the external mutex before
466 * calling signal() and broadcast(), whereas POSIX only requires grabbing
467 * it before calling wait(). The implementation here has been un-optimized
468 * to have the correct behavior.
469 */
470typedef struct WinCondition {
471 // Number of waiting threads.
472 int waitersCount;
473
474 // Serialize access to waitersCount.
475 CRITICAL_SECTION waitersCountLock;
476
477 // Semaphore used to queue up threads waiting for the condition to
478 // become signaled.
479 HANDLE sema;
480
481 // An auto-reset event used by the broadcast/signal thread to wait
482 // for all the waiting thread(s) to wake up and be released from
483 // the semaphore.
484 HANDLE waitersDone;
485
486 // This mutex wouldn't be necessary if we required that the caller
487 // lock the external mutex before calling signal() and broadcast().
488 // I'm trying to mimic pthread semantics though.
489 HANDLE internalMutex;
490
491 // Keeps track of whether we were broadcasting or signaling. This
492 // allows us to optimize the code if we're just signaling.
493 bool wasBroadcast;
494
495 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
496 {
497 // Increment the wait count, avoiding race conditions.
498 EnterCriticalSection(&condState->waitersCountLock);
499 condState->waitersCount++;
500 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
501 // condState->waitersCount, getThreadId());
502 LeaveCriticalSection(&condState->waitersCountLock);
503
504 DWORD timeout = INFINITE;
505 if (abstime) {
506 nsecs_t reltime = *abstime - systemTime();
507 if (reltime < 0)
508 reltime = 0;
509 timeout = reltime/1000000;
510 }
511
512 // Atomically release the external mutex and wait on the semaphore.
513 DWORD res =
514 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
515
516 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
517
518 // Reacquire lock to avoid race conditions.
519 EnterCriticalSection(&condState->waitersCountLock);
520
521 // No longer waiting.
522 condState->waitersCount--;
523
524 // Check to see if we're the last waiter after a broadcast.
525 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
526
527 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
528 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
529
530 LeaveCriticalSection(&condState->waitersCountLock);
531
532 // If we're the last waiter thread during this particular broadcast
533 // then signal broadcast() that we're all awake. It'll drop the
534 // internal mutex.
535 if (lastWaiter) {
536 // Atomically signal the "waitersDone" event and wait until we
537 // can acquire the internal mutex. We want to do this in one step
538 // because it ensures that everybody is in the mutex FIFO before
539 // any thread has a chance to run. Without it, another thread
540 // could wake up, do work, and hop back in ahead of us.
541 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
542 INFINITE, FALSE);
543 } else {
544 // Grab the internal mutex.
545 WaitForSingleObject(condState->internalMutex, INFINITE);
546 }
547
548 // Release the internal and grab the external.
549 ReleaseMutex(condState->internalMutex);
550 WaitForSingleObject(hMutex, INFINITE);
551
552 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
553 }
554} WinCondition;
555
556/*
557 * Constructor. Set up the WinCondition stuff.
558 */
559Condition::Condition()
560{
561 WinCondition* condState = new WinCondition;
562
563 condState->waitersCount = 0;
564 condState->wasBroadcast = false;
565 // semaphore: no security, initial value of 0
566 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
567 InitializeCriticalSection(&condState->waitersCountLock);
568 // auto-reset event, not signaled initially
569 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
570 // used so we don't have to lock external mutex on signal/broadcast
571 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
572
573 mState = condState;
574}
575
576/*
577 * Destructor. Free Windows resources as well as our allocated storage.
578 */
579Condition::~Condition()
580{
581 WinCondition* condState = (WinCondition*) mState;
582 if (condState != NULL) {
583 CloseHandle(condState->sema);
584 CloseHandle(condState->waitersDone);
585 delete condState;
586 }
587}
588
589
590status_t Condition::wait(Mutex& mutex)
591{
592 WinCondition* condState = (WinCondition*) mState;
593 HANDLE hMutex = (HANDLE) mutex.mState;
594
595 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
596}
597
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800598status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
599{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200600 WinCondition* condState = (WinCondition*) mState;
601 HANDLE hMutex = (HANDLE) mutex.mState;
602 nsecs_t absTime = systemTime()+reltime;
603
604 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800605}
606
607/*
608 * Signal the condition variable, allowing one thread to continue.
609 */
610void Condition::signal()
611{
612 WinCondition* condState = (WinCondition*) mState;
613
614 // Lock the internal mutex. This ensures that we don't clash with
615 // broadcast().
616 WaitForSingleObject(condState->internalMutex, INFINITE);
617
618 EnterCriticalSection(&condState->waitersCountLock);
619 bool haveWaiters = (condState->waitersCount > 0);
620 LeaveCriticalSection(&condState->waitersCountLock);
621
622 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
623 // down a notch.
624 if (haveWaiters)
625 ReleaseSemaphore(condState->sema, 1, 0);
626
627 // Release internal mutex.
628 ReleaseMutex(condState->internalMutex);
629}
630
631/*
632 * Signal the condition variable, allowing all threads to continue.
633 *
634 * First we have to wake up all threads waiting on the semaphore, then
635 * we wait until all of the threads have actually been woken before
636 * releasing the internal mutex. This ensures that all threads are woken.
637 */
638void Condition::broadcast()
639{
640 WinCondition* condState = (WinCondition*) mState;
641
642 // Lock the internal mutex. This keeps the guys we're waking up
643 // from getting too far.
644 WaitForSingleObject(condState->internalMutex, INFINITE);
645
646 EnterCriticalSection(&condState->waitersCountLock);
647 bool haveWaiters = false;
648
649 if (condState->waitersCount > 0) {
650 haveWaiters = true;
651 condState->wasBroadcast = true;
652 }
653
654 if (haveWaiters) {
655 // Wake up all the waiters.
656 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
657
658 LeaveCriticalSection(&condState->waitersCountLock);
659
660 // Wait for all awakened threads to acquire the counting semaphore.
661 // The last guy who was waiting sets this.
662 WaitForSingleObject(condState->waitersDone, INFINITE);
663
664 // Reset wasBroadcast. (No crit section needed because nobody
665 // else can wake up to poke at it.)
666 condState->wasBroadcast = 0;
667 } else {
668 // nothing to do
669 LeaveCriticalSection(&condState->waitersCountLock);
670 }
671
672 // Release internal mutex.
673 ReleaseMutex(condState->internalMutex);
674}
675
676#else
677#error "condition variables not supported on this platform"
678#endif
679
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800680// ----------------------------------------------------------------------------
681
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800682/*
683 * This is our thread object!
684 */
685
686Thread::Thread(bool canCallJava)
687 : mCanCallJava(canCallJava),
688 mThread(thread_id_t(-1)),
689 mLock("Thread::mLock"),
690 mStatus(NO_ERROR),
691 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800692#ifdef HAVE_ANDROID_OS
693 , mTid(-1)
694#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800695{
696}
697
698Thread::~Thread()
699{
700}
701
702status_t Thread::readyToRun()
703{
704 return NO_ERROR;
705}
706
707status_t Thread::run(const char* name, int32_t priority, size_t stack)
708{
709 Mutex::Autolock _l(mLock);
710
711 if (mRunning) {
712 // thread already started
713 return INVALID_OPERATION;
714 }
715
716 // reset status and exitPending to their default value, so we can
717 // try again after an error happened (either below, or in readyToRun())
718 mStatus = NO_ERROR;
719 mExitPending = false;
720 mThread = thread_id_t(-1);
721
722 // hold a strong reference on ourself
723 mHoldSelf = this;
724
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800725 mRunning = true;
726
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800727 bool res;
728 if (mCanCallJava) {
729 res = createThreadEtc(_threadLoop,
730 this, name, priority, stack, &mThread);
731 } else {
732 res = androidCreateRawThreadEtc(_threadLoop,
733 this, name, priority, stack, &mThread);
734 }
735
736 if (res == false) {
737 mStatus = UNKNOWN_ERROR; // something happened!
738 mRunning = false;
739 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800740 mHoldSelf.clear(); // "this" may have gone away after this.
741
742 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800743 }
744
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800745 // Do not refer to mStatus here: The thread is already running (may, in fact
746 // already have exited with a valid mStatus result). The NO_ERROR indication
747 // here merely indicates successfully starting the thread and does not
748 // imply successful termination/execution.
749 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800750
751 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800752}
753
754int Thread::_threadLoop(void* user)
755{
756 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800757
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800758 sp<Thread> strong(self->mHoldSelf);
759 wp<Thread> weak(strong);
760 self->mHoldSelf.clear();
761
Kenny Rootdafff0b2011-02-16 10:13:53 -0800762#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700763 // this is very useful for debugging with gdb
764 self->mTid = gettid();
765#endif
766
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800767 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800768
769 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800770 bool result;
771 if (first) {
772 first = false;
773 self->mStatus = self->readyToRun();
774 result = (self->mStatus == NO_ERROR);
775
Glenn Kasten966a48f2011-02-01 11:32:29 -0800776 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800777 // Binder threads (and maybe others) rely on threadLoop
778 // running at least once after a successful ::readyToRun()
779 // (unless, of course, the thread has already been asked to exit
780 // at that point).
781 // This is because threads are essentially used like this:
782 // (new ThreadSubclass())->run();
783 // The caller therefore does not retain a strong reference to
784 // the thread and the thread would simply disappear after the
785 // successful ::readyToRun() call instead of entering the
786 // threadLoop at least once.
787 result = self->threadLoop();
788 }
789 } else {
790 result = self->threadLoop();
791 }
792
Glenn Kasten966a48f2011-02-01 11:32:29 -0800793 // establish a scope for mLock
794 {
795 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800796 if (result == false || self->mExitPending) {
797 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800798 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800799 // clear thread ID so that requestExitAndWait() does not exit if
800 // called by a new thread using the same thread ID as this one.
801 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800802 // note that interested observers blocked in requestExitAndWait are
803 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700804 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800805 break;
806 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800807 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800808
809 // Release our strong reference, to let a chance to the thread
810 // to die a peaceful death.
811 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700812 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800813 strong = weak.promote();
814 } while(strong != 0);
815
816 return 0;
817}
818
819void Thread::requestExit()
820{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800821 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800822 mExitPending = true;
823}
824
825status_t Thread::requestExitAndWait()
826{
Glenn Kastena538e262011-06-02 08:59:28 -0700827 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800828 if (mThread == getThreadId()) {
829 LOGW(
830 "Thread (this=%p): don't call waitForExit() from this "
831 "Thread object's thread. It's a guaranteed deadlock!",
832 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800833
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800834 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800835 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800836
Glenn Kastena538e262011-06-02 08:59:28 -0700837 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800838
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800839 while (mRunning == true) {
840 mThreadExitedCondition.wait(mLock);
841 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800842 // This next line is probably not needed any more, but is being left for
843 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800844 mExitPending = false;
845
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800846 return mStatus;
847}
848
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700849status_t Thread::join()
850{
851 Mutex::Autolock _l(mLock);
852 if (mThread == getThreadId()) {
853 LOGW(
854 "Thread (this=%p): don't call join() from this "
855 "Thread object's thread. It's a guaranteed deadlock!",
856 this);
857
858 return WOULD_BLOCK;
859 }
860
861 while (mRunning == true) {
862 mThreadExitedCondition.wait(mLock);
863 }
864
865 return mStatus;
866}
867
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800868bool Thread::exitPending() const
869{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800870 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800871 return mExitPending;
872}
873
874
875
876}; // namespace android