blob: f201fc74471d4429bc236194e9a3702434e66937 [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>
Glenn Kastend731f072011-07-11 15:59:22 -070037#ifdef HAVE_ANDROID_OS
38# include <bionic_pthread.h>
39#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080040#elif defined(HAVE_WIN32_THREADS)
41# include <windows.h>
42# include <stdint.h>
43# include <process.h>
44# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
45#endif
46
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080047#if defined(HAVE_PRCTL)
48#include <sys/prctl.h>
49#endif
50
51/*
52 * ===========================================================================
53 * Thread wrappers
54 * ===========================================================================
55 */
56
57using namespace android;
58
59// ----------------------------------------------------------------------------
60#if defined(HAVE_PTHREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080061// ----------------------------------------------------------------------------
62
63/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070064 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080065 *
66 * We create it "detached", so it cleans up after itself.
67 */
68
69typedef void* (*android_pthread_entry)(void*);
70
71struct 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
Glenn Kastend731f072011-07-11 15:59:22 -070078 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080079 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);
Glenn Kastenfe34e452012-04-30 16:03:30 -070086 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
87 set_sched_policy(0, SP_BACKGROUND);
88 } else {
89 set_sched_policy(0, SP_FOREGROUND);
Dianne Hackborna78bab02010-09-09 15:50:18 -070090 }
91
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080092 if (name) {
93#if defined(HAVE_PRCTL)
94 // Mac OS doesn't have this, and we build libutil for the host too
95 int hasAt = 0;
96 int hasDot = 0;
97 char *s = name;
98 while (*s) {
99 if (*s == '.') hasDot = 1;
100 else if (*s == '@') hasAt = 1;
101 s++;
102 }
103 int len = s - name;
104 if (len < 15 || hasAt || !hasDot) {
105 s = name;
106 } else {
107 s = name + len - 15;
108 }
109 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
110#endif
111 free(name);
112 }
113 return f(u);
114 }
115};
116
117int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
118 void *userData,
119 const char* threadName,
120 int32_t threadPriority,
121 size_t threadStackSize,
122 android_thread_id_t *threadId)
123{
124 pthread_attr_t attr;
125 pthread_attr_init(&attr);
126 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
127
128#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
129 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700130 // Now that the pthread_t has a method to find the associated
131 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
132 // this trampoline in some cases as the parent could set the properties
133 // for the child. However, there would be a race condition because the
134 // child becomes ready immediately, and it doesn't work for the name.
135 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
136 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800137 thread_data_t* t = new thread_data_t;
138 t->priority = threadPriority;
139 t->threadName = threadName ? strdup(threadName) : NULL;
140 t->entryFunction = entryFunction;
141 t->userData = userData;
142 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
143 userData = t;
144 }
145#endif
146
147 if (threadStackSize) {
148 pthread_attr_setstacksize(&attr, threadStackSize);
149 }
150
151 errno = 0;
152 pthread_t thread;
153 int result = pthread_create(&thread, &attr,
154 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700155 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800156 if (result != 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000157 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800158 "(android threadPriority=%d)",
159 entryFunction, result, errno, threadPriority);
160 return 0;
161 }
162
Glenn Kastena538e262011-06-02 08:59:28 -0700163 // Note that *threadID is directly available to the parent only, as it is
164 // assigned after the child starts. Use memory barrier / lock if the child
165 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800166 if (threadId != NULL) {
167 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
168 }
169 return 1;
170}
171
Glenn Kastend731f072011-07-11 15:59:22 -0700172#ifdef HAVE_ANDROID_OS
173static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
174{
175 return (pthread_t) thread;
176}
177#endif
178
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800179android_thread_id_t androidGetThreadId()
180{
181 return (android_thread_id_t)pthread_self();
182}
183
184// ----------------------------------------------------------------------------
185#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800186// ----------------------------------------------------------------------------
187
188/*
189 * Trampoline to make us __stdcall-compliant.
190 *
191 * We're expected to delete "vDetails" when we're done.
192 */
193struct threadDetails {
194 int (*func)(void*);
195 void* arg;
196};
197static __stdcall unsigned int threadIntermediary(void* vDetails)
198{
199 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
200 int result;
201
202 result = (*(pDetails->func))(pDetails->arg);
203
204 delete pDetails;
205
Steve Block8b4cf772011-10-12 17:27:03 +0100206 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800207 return (unsigned int) result;
208}
209
210/*
211 * Create and run a new thread.
212 */
213static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
214{
215 HANDLE hThread;
216 struct threadDetails* pDetails = new threadDetails; // must be on heap
217 unsigned int thrdaddr;
218
219 pDetails->func = fn;
220 pDetails->arg = arg;
221
222#if defined(HAVE__BEGINTHREADEX)
223 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
224 &thrdaddr);
225 if (hThread == 0)
226#elif defined(HAVE_CREATETHREAD)
227 hThread = CreateThread(NULL, 0,
228 (LPTHREAD_START_ROUTINE) threadIntermediary,
229 (void*) pDetails, 0, (DWORD*) &thrdaddr);
230 if (hThread == NULL)
231#endif
232 {
Steve Block8b4cf772011-10-12 17:27:03 +0100233 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800234 return false;
235 }
236
237#if defined(HAVE_CREATETHREAD)
238 /* close the management handle */
239 CloseHandle(hThread);
240#endif
241
242 if (id != NULL) {
243 *id = (android_thread_id_t)thrdaddr;
244 }
245
246 return true;
247}
248
249int androidCreateRawThreadEtc(android_thread_func_t fn,
250 void *userData,
251 const char* threadName,
252 int32_t threadPriority,
253 size_t threadStackSize,
254 android_thread_id_t *threadId)
255{
256 return doCreateThread( fn, userData, threadId);
257}
258
259android_thread_id_t androidGetThreadId()
260{
261 return (android_thread_id_t)GetCurrentThreadId();
262}
263
264// ----------------------------------------------------------------------------
265#else
266#error "Threads not supported"
267#endif
268
269// ----------------------------------------------------------------------------
270
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800271int androidCreateThread(android_thread_func_t fn, void* arg)
272{
273 return createThreadEtc(fn, arg);
274}
275
276int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
277{
278 return createThreadEtc(fn, arg, "android:unnamed_thread",
279 PRIORITY_DEFAULT, 0, id);
280}
281
282static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
283
284int androidCreateThreadEtc(android_thread_func_t entryFunction,
285 void *userData,
286 const char* threadName,
287 int32_t threadPriority,
288 size_t threadStackSize,
289 android_thread_id_t *threadId)
290{
291 return gCreateThreadFn(entryFunction, userData, threadName,
292 threadPriority, threadStackSize, threadId);
293}
294
295void androidSetCreateThreadFunc(android_create_thread_fn func)
296{
297 gCreateThreadFn = func;
298}
299
Dianne Hackborn235af972009-12-07 17:59:37 -0800300pid_t androidGetTid()
301{
302#ifdef HAVE_GETTID
303 return gettid();
304#else
305 return getpid();
306#endif
307}
308
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700309#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800310int androidSetThreadPriority(pid_t tid, int pri)
311{
312 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800313
314#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800315 int lasterr = 0;
316
Glenn Kastenfe34e452012-04-30 16:03:30 -0700317 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
318 rc = set_sched_policy(tid, SP_BACKGROUND);
319 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
320 rc = set_sched_policy(tid, SP_FOREGROUND);
Dianne Hackborn235af972009-12-07 17:59:37 -0800321 }
322
323 if (rc) {
324 lasterr = errno;
325 }
326
327 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
328 rc = INVALID_OPERATION;
329 } else {
330 errno = lasterr;
331 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800332#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800333
334 return rc;
335}
336
Andreas Huber8ddbed92011-09-15 12:21:40 -0700337int androidGetThreadPriority(pid_t tid) {
Andreas Huber7b4ce612011-09-16 11:47:13 -0700338#if defined(HAVE_PTHREADS)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700339 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700340#else
341 return ANDROID_PRIORITY_NORMAL;
342#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700343}
344
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700345#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700346
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800347namespace android {
348
349/*
350 * ===========================================================================
351 * Mutex class
352 * ===========================================================================
353 */
354
Mathias Agopian15554362009-07-12 23:11:20 -0700355#if defined(HAVE_PTHREADS)
356// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800357#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800358
359Mutex::Mutex()
360{
361 HANDLE hMutex;
362
363 assert(sizeof(hMutex) == sizeof(mState));
364
365 hMutex = CreateMutex(NULL, FALSE, NULL);
366 mState = (void*) hMutex;
367}
368
369Mutex::Mutex(const char* name)
370{
371 // XXX: name not used for now
372 HANDLE hMutex;
373
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200374 assert(sizeof(hMutex) == sizeof(mState));
375
376 hMutex = CreateMutex(NULL, FALSE, NULL);
377 mState = (void*) hMutex;
378}
379
380Mutex::Mutex(int type, const char* name)
381{
382 // XXX: type and name not used for now
383 HANDLE hMutex;
384
385 assert(sizeof(hMutex) == sizeof(mState));
386
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800387 hMutex = CreateMutex(NULL, FALSE, NULL);
388 mState = (void*) hMutex;
389}
390
391Mutex::~Mutex()
392{
393 CloseHandle((HANDLE) mState);
394}
395
396status_t Mutex::lock()
397{
398 DWORD dwWaitResult;
399 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
400 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
401}
402
403void Mutex::unlock()
404{
405 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100406 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800407}
408
409status_t Mutex::tryLock()
410{
411 DWORD dwWaitResult;
412
413 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
414 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100415 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800416 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
417}
418
419#else
420#error "Somebody forgot to implement threads for this platform."
421#endif
422
423
424/*
425 * ===========================================================================
426 * Condition class
427 * ===========================================================================
428 */
429
Mathias Agopian15554362009-07-12 23:11:20 -0700430#if defined(HAVE_PTHREADS)
431// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800432#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800433
434/*
435 * Windows doesn't have a condition variable solution. It's possible
436 * to create one, but it's easy to get it wrong. For a discussion, and
437 * the origin of this implementation, see:
438 *
439 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
440 *
441 * The implementation shown on the page does NOT follow POSIX semantics.
442 * As an optimization they require acquiring the external mutex before
443 * calling signal() and broadcast(), whereas POSIX only requires grabbing
444 * it before calling wait(). The implementation here has been un-optimized
445 * to have the correct behavior.
446 */
447typedef struct WinCondition {
448 // Number of waiting threads.
449 int waitersCount;
450
451 // Serialize access to waitersCount.
452 CRITICAL_SECTION waitersCountLock;
453
454 // Semaphore used to queue up threads waiting for the condition to
455 // become signaled.
456 HANDLE sema;
457
458 // An auto-reset event used by the broadcast/signal thread to wait
459 // for all the waiting thread(s) to wake up and be released from
460 // the semaphore.
461 HANDLE waitersDone;
462
463 // This mutex wouldn't be necessary if we required that the caller
464 // lock the external mutex before calling signal() and broadcast().
465 // I'm trying to mimic pthread semantics though.
466 HANDLE internalMutex;
467
468 // Keeps track of whether we were broadcasting or signaling. This
469 // allows us to optimize the code if we're just signaling.
470 bool wasBroadcast;
471
472 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
473 {
474 // Increment the wait count, avoiding race conditions.
475 EnterCriticalSection(&condState->waitersCountLock);
476 condState->waitersCount++;
477 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
478 // condState->waitersCount, getThreadId());
479 LeaveCriticalSection(&condState->waitersCountLock);
480
481 DWORD timeout = INFINITE;
482 if (abstime) {
483 nsecs_t reltime = *abstime - systemTime();
484 if (reltime < 0)
485 reltime = 0;
486 timeout = reltime/1000000;
487 }
488
489 // Atomically release the external mutex and wait on the semaphore.
490 DWORD res =
491 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
492
493 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
494
495 // Reacquire lock to avoid race conditions.
496 EnterCriticalSection(&condState->waitersCountLock);
497
498 // No longer waiting.
499 condState->waitersCount--;
500
501 // Check to see if we're the last waiter after a broadcast.
502 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
503
504 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
505 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
506
507 LeaveCriticalSection(&condState->waitersCountLock);
508
509 // If we're the last waiter thread during this particular broadcast
510 // then signal broadcast() that we're all awake. It'll drop the
511 // internal mutex.
512 if (lastWaiter) {
513 // Atomically signal the "waitersDone" event and wait until we
514 // can acquire the internal mutex. We want to do this in one step
515 // because it ensures that everybody is in the mutex FIFO before
516 // any thread has a chance to run. Without it, another thread
517 // could wake up, do work, and hop back in ahead of us.
518 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
519 INFINITE, FALSE);
520 } else {
521 // Grab the internal mutex.
522 WaitForSingleObject(condState->internalMutex, INFINITE);
523 }
524
525 // Release the internal and grab the external.
526 ReleaseMutex(condState->internalMutex);
527 WaitForSingleObject(hMutex, INFINITE);
528
529 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
530 }
531} WinCondition;
532
533/*
534 * Constructor. Set up the WinCondition stuff.
535 */
536Condition::Condition()
537{
538 WinCondition* condState = new WinCondition;
539
540 condState->waitersCount = 0;
541 condState->wasBroadcast = false;
542 // semaphore: no security, initial value of 0
543 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
544 InitializeCriticalSection(&condState->waitersCountLock);
545 // auto-reset event, not signaled initially
546 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
547 // used so we don't have to lock external mutex on signal/broadcast
548 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
549
550 mState = condState;
551}
552
553/*
554 * Destructor. Free Windows resources as well as our allocated storage.
555 */
556Condition::~Condition()
557{
558 WinCondition* condState = (WinCondition*) mState;
559 if (condState != NULL) {
560 CloseHandle(condState->sema);
561 CloseHandle(condState->waitersDone);
562 delete condState;
563 }
564}
565
566
567status_t Condition::wait(Mutex& mutex)
568{
569 WinCondition* condState = (WinCondition*) mState;
570 HANDLE hMutex = (HANDLE) mutex.mState;
571
572 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
573}
574
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800575status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
576{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200577 WinCondition* condState = (WinCondition*) mState;
578 HANDLE hMutex = (HANDLE) mutex.mState;
579 nsecs_t absTime = systemTime()+reltime;
580
581 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800582}
583
584/*
585 * Signal the condition variable, allowing one thread to continue.
586 */
587void Condition::signal()
588{
589 WinCondition* condState = (WinCondition*) mState;
590
591 // Lock the internal mutex. This ensures that we don't clash with
592 // broadcast().
593 WaitForSingleObject(condState->internalMutex, INFINITE);
594
595 EnterCriticalSection(&condState->waitersCountLock);
596 bool haveWaiters = (condState->waitersCount > 0);
597 LeaveCriticalSection(&condState->waitersCountLock);
598
599 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
600 // down a notch.
601 if (haveWaiters)
602 ReleaseSemaphore(condState->sema, 1, 0);
603
604 // Release internal mutex.
605 ReleaseMutex(condState->internalMutex);
606}
607
608/*
609 * Signal the condition variable, allowing all threads to continue.
610 *
611 * First we have to wake up all threads waiting on the semaphore, then
612 * we wait until all of the threads have actually been woken before
613 * releasing the internal mutex. This ensures that all threads are woken.
614 */
615void Condition::broadcast()
616{
617 WinCondition* condState = (WinCondition*) mState;
618
619 // Lock the internal mutex. This keeps the guys we're waking up
620 // from getting too far.
621 WaitForSingleObject(condState->internalMutex, INFINITE);
622
623 EnterCriticalSection(&condState->waitersCountLock);
624 bool haveWaiters = false;
625
626 if (condState->waitersCount > 0) {
627 haveWaiters = true;
628 condState->wasBroadcast = true;
629 }
630
631 if (haveWaiters) {
632 // Wake up all the waiters.
633 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
634
635 LeaveCriticalSection(&condState->waitersCountLock);
636
637 // Wait for all awakened threads to acquire the counting semaphore.
638 // The last guy who was waiting sets this.
639 WaitForSingleObject(condState->waitersDone, INFINITE);
640
641 // Reset wasBroadcast. (No crit section needed because nobody
642 // else can wake up to poke at it.)
643 condState->wasBroadcast = 0;
644 } else {
645 // nothing to do
646 LeaveCriticalSection(&condState->waitersCountLock);
647 }
648
649 // Release internal mutex.
650 ReleaseMutex(condState->internalMutex);
651}
652
653#else
654#error "condition variables not supported on this platform"
655#endif
656
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800657// ----------------------------------------------------------------------------
658
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800659/*
660 * This is our thread object!
661 */
662
663Thread::Thread(bool canCallJava)
664 : mCanCallJava(canCallJava),
665 mThread(thread_id_t(-1)),
666 mLock("Thread::mLock"),
667 mStatus(NO_ERROR),
668 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800669#ifdef HAVE_ANDROID_OS
670 , mTid(-1)
671#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800672{
673}
674
675Thread::~Thread()
676{
677}
678
679status_t Thread::readyToRun()
680{
681 return NO_ERROR;
682}
683
684status_t Thread::run(const char* name, int32_t priority, size_t stack)
685{
686 Mutex::Autolock _l(mLock);
687
688 if (mRunning) {
689 // thread already started
690 return INVALID_OPERATION;
691 }
692
693 // reset status and exitPending to their default value, so we can
694 // try again after an error happened (either below, or in readyToRun())
695 mStatus = NO_ERROR;
696 mExitPending = false;
697 mThread = thread_id_t(-1);
698
699 // hold a strong reference on ourself
700 mHoldSelf = this;
701
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800702 mRunning = true;
703
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800704 bool res;
705 if (mCanCallJava) {
706 res = createThreadEtc(_threadLoop,
707 this, name, priority, stack, &mThread);
708 } else {
709 res = androidCreateRawThreadEtc(_threadLoop,
710 this, name, priority, stack, &mThread);
711 }
712
713 if (res == false) {
714 mStatus = UNKNOWN_ERROR; // something happened!
715 mRunning = false;
716 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800717 mHoldSelf.clear(); // "this" may have gone away after this.
718
719 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800720 }
721
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800722 // Do not refer to mStatus here: The thread is already running (may, in fact
723 // already have exited with a valid mStatus result). The NO_ERROR indication
724 // here merely indicates successfully starting the thread and does not
725 // imply successful termination/execution.
726 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800727
728 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800729}
730
731int Thread::_threadLoop(void* user)
732{
733 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800734
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800735 sp<Thread> strong(self->mHoldSelf);
736 wp<Thread> weak(strong);
737 self->mHoldSelf.clear();
738
Kenny Rootdafff0b2011-02-16 10:13:53 -0800739#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700740 // this is very useful for debugging with gdb
741 self->mTid = gettid();
742#endif
743
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800744 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800745
746 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800747 bool result;
748 if (first) {
749 first = false;
750 self->mStatus = self->readyToRun();
751 result = (self->mStatus == NO_ERROR);
752
Glenn Kasten966a48f2011-02-01 11:32:29 -0800753 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800754 // Binder threads (and maybe others) rely on threadLoop
755 // running at least once after a successful ::readyToRun()
756 // (unless, of course, the thread has already been asked to exit
757 // at that point).
758 // This is because threads are essentially used like this:
759 // (new ThreadSubclass())->run();
760 // The caller therefore does not retain a strong reference to
761 // the thread and the thread would simply disappear after the
762 // successful ::readyToRun() call instead of entering the
763 // threadLoop at least once.
764 result = self->threadLoop();
765 }
766 } else {
767 result = self->threadLoop();
768 }
769
Glenn Kasten966a48f2011-02-01 11:32:29 -0800770 // establish a scope for mLock
771 {
772 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800773 if (result == false || self->mExitPending) {
774 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800775 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800776 // clear thread ID so that requestExitAndWait() does not exit if
777 // called by a new thread using the same thread ID as this one.
778 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800779 // note that interested observers blocked in requestExitAndWait are
780 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700781 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800782 break;
783 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800784 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800785
786 // Release our strong reference, to let a chance to the thread
787 // to die a peaceful death.
788 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700789 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800790 strong = weak.promote();
791 } while(strong != 0);
792
793 return 0;
794}
795
796void Thread::requestExit()
797{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800798 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800799 mExitPending = true;
800}
801
802status_t Thread::requestExitAndWait()
803{
Glenn Kastena538e262011-06-02 08:59:28 -0700804 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800805 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000806 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800807 "Thread (this=%p): don't call waitForExit() from this "
808 "Thread object's thread. It's a guaranteed deadlock!",
809 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800810
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800811 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800812 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800813
Glenn Kastena538e262011-06-02 08:59:28 -0700814 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800815
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800816 while (mRunning == true) {
817 mThreadExitedCondition.wait(mLock);
818 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800819 // This next line is probably not needed any more, but is being left for
820 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800821 mExitPending = false;
822
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800823 return mStatus;
824}
825
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700826status_t Thread::join()
827{
828 Mutex::Autolock _l(mLock);
829 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000830 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700831 "Thread (this=%p): don't call join() from this "
832 "Thread object's thread. It's a guaranteed deadlock!",
833 this);
834
835 return WOULD_BLOCK;
836 }
837
838 while (mRunning == true) {
839 mThreadExitedCondition.wait(mLock);
840 }
841
842 return mStatus;
843}
844
Glenn Kastend731f072011-07-11 15:59:22 -0700845#ifdef HAVE_ANDROID_OS
846pid_t Thread::getTid() const
847{
848 // mTid is not defined until the child initializes it, and the caller may need it earlier
849 Mutex::Autolock _l(mLock);
850 pid_t tid;
851 if (mRunning) {
852 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
853 tid = __pthread_gettid(pthread);
854 } else {
855 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
856 tid = -1;
857 }
858 return tid;
859}
860#endif
861
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800862bool Thread::exitPending() const
863{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800864 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800865 return mExitPending;
866}
867
868
869
870}; // namespace android