blob: cbf4ef628c0d7d5829997f8e0a900a03c4ceb28b [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>
Nick Kralevichd30884a2013-02-02 18:09:15 -080024#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) {
Mathias Agopian6090df82013-03-07 15:34:28 -080093 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080094 free(name);
95 }
96 return f(u);
97 }
98};
99
Mathias Agopian6090df82013-03-07 15:34:28 -0800100void androidSetThreadName(const char* name) {
101#if defined(HAVE_PRCTL)
102 // Mac OS doesn't have this, and we build libutil for the host too
103 int hasAt = 0;
104 int hasDot = 0;
105 const char *s = name;
106 while (*s) {
107 if (*s == '.') hasDot = 1;
108 else if (*s == '@') hasAt = 1;
109 s++;
110 }
111 int len = s - name;
112 if (len < 15 || hasAt || !hasDot) {
113 s = name;
114 } else {
115 s = name + len - 15;
116 }
117 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
118#endif
119}
120
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800121int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
122 void *userData,
123 const char* threadName,
124 int32_t threadPriority,
125 size_t threadStackSize,
126 android_thread_id_t *threadId)
127{
128 pthread_attr_t attr;
129 pthread_attr_init(&attr);
130 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
131
132#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
133 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700134 // Now that the pthread_t has a method to find the associated
135 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
136 // this trampoline in some cases as the parent could set the properties
137 // for the child. However, there would be a race condition because the
138 // child becomes ready immediately, and it doesn't work for the name.
139 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
140 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800141 thread_data_t* t = new thread_data_t;
142 t->priority = threadPriority;
143 t->threadName = threadName ? strdup(threadName) : NULL;
144 t->entryFunction = entryFunction;
145 t->userData = userData;
146 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
147 userData = t;
148 }
149#endif
150
151 if (threadStackSize) {
152 pthread_attr_setstacksize(&attr, threadStackSize);
153 }
154
155 errno = 0;
156 pthread_t thread;
157 int result = pthread_create(&thread, &attr,
158 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700159 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800160 if (result != 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000161 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800162 "(android threadPriority=%d)",
163 entryFunction, result, errno, threadPriority);
164 return 0;
165 }
166
Glenn Kastena538e262011-06-02 08:59:28 -0700167 // Note that *threadID is directly available to the parent only, as it is
168 // assigned after the child starts. Use memory barrier / lock if the child
169 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800170 if (threadId != NULL) {
171 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
172 }
173 return 1;
174}
175
Glenn Kastend731f072011-07-11 15:59:22 -0700176#ifdef HAVE_ANDROID_OS
177static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
178{
179 return (pthread_t) thread;
180}
181#endif
182
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800183android_thread_id_t androidGetThreadId()
184{
185 return (android_thread_id_t)pthread_self();
186}
187
188// ----------------------------------------------------------------------------
189#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800190// ----------------------------------------------------------------------------
191
192/*
193 * Trampoline to make us __stdcall-compliant.
194 *
195 * We're expected to delete "vDetails" when we're done.
196 */
197struct threadDetails {
198 int (*func)(void*);
199 void* arg;
200};
201static __stdcall unsigned int threadIntermediary(void* vDetails)
202{
203 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
204 int result;
205
206 result = (*(pDetails->func))(pDetails->arg);
207
208 delete pDetails;
209
Steve Block8b4cf772011-10-12 17:27:03 +0100210 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800211 return (unsigned int) result;
212}
213
214/*
215 * Create and run a new thread.
216 */
217static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
218{
219 HANDLE hThread;
220 struct threadDetails* pDetails = new threadDetails; // must be on heap
221 unsigned int thrdaddr;
222
223 pDetails->func = fn;
224 pDetails->arg = arg;
225
226#if defined(HAVE__BEGINTHREADEX)
227 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
228 &thrdaddr);
229 if (hThread == 0)
230#elif defined(HAVE_CREATETHREAD)
231 hThread = CreateThread(NULL, 0,
232 (LPTHREAD_START_ROUTINE) threadIntermediary,
233 (void*) pDetails, 0, (DWORD*) &thrdaddr);
234 if (hThread == NULL)
235#endif
236 {
Steve Block8b4cf772011-10-12 17:27:03 +0100237 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800238 return false;
239 }
240
241#if defined(HAVE_CREATETHREAD)
242 /* close the management handle */
243 CloseHandle(hThread);
244#endif
245
246 if (id != NULL) {
247 *id = (android_thread_id_t)thrdaddr;
248 }
249
250 return true;
251}
252
253int androidCreateRawThreadEtc(android_thread_func_t fn,
254 void *userData,
255 const char* threadName,
256 int32_t threadPriority,
257 size_t threadStackSize,
258 android_thread_id_t *threadId)
259{
260 return doCreateThread( fn, userData, threadId);
261}
262
263android_thread_id_t androidGetThreadId()
264{
265 return (android_thread_id_t)GetCurrentThreadId();
266}
267
268// ----------------------------------------------------------------------------
269#else
270#error "Threads not supported"
271#endif
272
273// ----------------------------------------------------------------------------
274
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800275int androidCreateThread(android_thread_func_t fn, void* arg)
276{
277 return createThreadEtc(fn, arg);
278}
279
280int 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
286static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
287
288int 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
299void androidSetCreateThreadFunc(android_create_thread_fn func)
300{
301 gCreateThreadFn = func;
302}
303
Dianne Hackborn235af972009-12-07 17:59:37 -0800304pid_t androidGetTid()
305{
306#ifdef HAVE_GETTID
307 return gettid();
308#else
309 return getpid();
310#endif
311}
312
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700313#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800314int androidSetThreadPriority(pid_t tid, int pri)
315{
316 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800317
318#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800319 int lasterr = 0;
320
Glenn Kastenfe34e452012-04-30 16:03:30 -0700321 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
322 rc = set_sched_policy(tid, SP_BACKGROUND);
323 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
324 rc = set_sched_policy(tid, SP_FOREGROUND);
Dianne Hackborn235af972009-12-07 17:59:37 -0800325 }
326
327 if (rc) {
328 lasterr = errno;
329 }
330
331 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
332 rc = INVALID_OPERATION;
333 } else {
334 errno = lasterr;
335 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800336#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800337
338 return rc;
339}
340
Andreas Huber8ddbed92011-09-15 12:21:40 -0700341int androidGetThreadPriority(pid_t tid) {
Andreas Huber7b4ce612011-09-16 11:47:13 -0700342#if defined(HAVE_PTHREADS)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700343 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700344#else
345 return ANDROID_PRIORITY_NORMAL;
346#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700347}
348
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700349#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700350
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800351namespace android {
352
353/*
354 * ===========================================================================
355 * Mutex class
356 * ===========================================================================
357 */
358
Mathias Agopian15554362009-07-12 23:11:20 -0700359#if defined(HAVE_PTHREADS)
360// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800361#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800362
363Mutex::Mutex()
364{
365 HANDLE hMutex;
366
367 assert(sizeof(hMutex) == sizeof(mState));
368
369 hMutex = CreateMutex(NULL, FALSE, NULL);
370 mState = (void*) hMutex;
371}
372
373Mutex::Mutex(const char* name)
374{
375 // XXX: name not used for now
376 HANDLE hMutex;
377
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200378 assert(sizeof(hMutex) == sizeof(mState));
379
380 hMutex = CreateMutex(NULL, FALSE, NULL);
381 mState = (void*) hMutex;
382}
383
384Mutex::Mutex(int type, const char* name)
385{
386 // XXX: type and name not used for now
387 HANDLE hMutex;
388
389 assert(sizeof(hMutex) == sizeof(mState));
390
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391 hMutex = CreateMutex(NULL, FALSE, NULL);
392 mState = (void*) hMutex;
393}
394
395Mutex::~Mutex()
396{
397 CloseHandle((HANDLE) mState);
398}
399
400status_t Mutex::lock()
401{
402 DWORD dwWaitResult;
403 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
404 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
405}
406
407void Mutex::unlock()
408{
409 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100410 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800411}
412
413status_t Mutex::tryLock()
414{
415 DWORD dwWaitResult;
416
417 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
418 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100419 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800420 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
421}
422
423#else
424#error "Somebody forgot to implement threads for this platform."
425#endif
426
427
428/*
429 * ===========================================================================
430 * Condition class
431 * ===========================================================================
432 */
433
Mathias Agopian15554362009-07-12 23:11:20 -0700434#if defined(HAVE_PTHREADS)
435// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800436#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800437
438/*
439 * Windows doesn't have a condition variable solution. It's possible
440 * to create one, but it's easy to get it wrong. For a discussion, and
441 * the origin of this implementation, see:
442 *
443 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
444 *
445 * The implementation shown on the page does NOT follow POSIX semantics.
446 * As an optimization they require acquiring the external mutex before
447 * calling signal() and broadcast(), whereas POSIX only requires grabbing
448 * it before calling wait(). The implementation here has been un-optimized
449 * to have the correct behavior.
450 */
451typedef struct WinCondition {
452 // Number of waiting threads.
453 int waitersCount;
454
455 // Serialize access to waitersCount.
456 CRITICAL_SECTION waitersCountLock;
457
458 // Semaphore used to queue up threads waiting for the condition to
459 // become signaled.
460 HANDLE sema;
461
462 // An auto-reset event used by the broadcast/signal thread to wait
463 // for all the waiting thread(s) to wake up and be released from
464 // the semaphore.
465 HANDLE waitersDone;
466
467 // This mutex wouldn't be necessary if we required that the caller
468 // lock the external mutex before calling signal() and broadcast().
469 // I'm trying to mimic pthread semantics though.
470 HANDLE internalMutex;
471
472 // Keeps track of whether we were broadcasting or signaling. This
473 // allows us to optimize the code if we're just signaling.
474 bool wasBroadcast;
475
476 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
477 {
478 // Increment the wait count, avoiding race conditions.
479 EnterCriticalSection(&condState->waitersCountLock);
480 condState->waitersCount++;
481 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
482 // condState->waitersCount, getThreadId());
483 LeaveCriticalSection(&condState->waitersCountLock);
484
485 DWORD timeout = INFINITE;
486 if (abstime) {
487 nsecs_t reltime = *abstime - systemTime();
488 if (reltime < 0)
489 reltime = 0;
490 timeout = reltime/1000000;
491 }
492
493 // Atomically release the external mutex and wait on the semaphore.
494 DWORD res =
495 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
496
497 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
498
499 // Reacquire lock to avoid race conditions.
500 EnterCriticalSection(&condState->waitersCountLock);
501
502 // No longer waiting.
503 condState->waitersCount--;
504
505 // Check to see if we're the last waiter after a broadcast.
506 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
507
508 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
509 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
510
511 LeaveCriticalSection(&condState->waitersCountLock);
512
513 // If we're the last waiter thread during this particular broadcast
514 // then signal broadcast() that we're all awake. It'll drop the
515 // internal mutex.
516 if (lastWaiter) {
517 // Atomically signal the "waitersDone" event and wait until we
518 // can acquire the internal mutex. We want to do this in one step
519 // because it ensures that everybody is in the mutex FIFO before
520 // any thread has a chance to run. Without it, another thread
521 // could wake up, do work, and hop back in ahead of us.
522 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
523 INFINITE, FALSE);
524 } else {
525 // Grab the internal mutex.
526 WaitForSingleObject(condState->internalMutex, INFINITE);
527 }
528
529 // Release the internal and grab the external.
530 ReleaseMutex(condState->internalMutex);
531 WaitForSingleObject(hMutex, INFINITE);
532
533 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
534 }
535} WinCondition;
536
537/*
538 * Constructor. Set up the WinCondition stuff.
539 */
540Condition::Condition()
541{
542 WinCondition* condState = new WinCondition;
543
544 condState->waitersCount = 0;
545 condState->wasBroadcast = false;
546 // semaphore: no security, initial value of 0
547 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
548 InitializeCriticalSection(&condState->waitersCountLock);
549 // auto-reset event, not signaled initially
550 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
551 // used so we don't have to lock external mutex on signal/broadcast
552 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
553
554 mState = condState;
555}
556
557/*
558 * Destructor. Free Windows resources as well as our allocated storage.
559 */
560Condition::~Condition()
561{
562 WinCondition* condState = (WinCondition*) mState;
563 if (condState != NULL) {
564 CloseHandle(condState->sema);
565 CloseHandle(condState->waitersDone);
566 delete condState;
567 }
568}
569
570
571status_t Condition::wait(Mutex& mutex)
572{
573 WinCondition* condState = (WinCondition*) mState;
574 HANDLE hMutex = (HANDLE) mutex.mState;
575
576 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
577}
578
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800579status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
580{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200581 WinCondition* condState = (WinCondition*) mState;
582 HANDLE hMutex = (HANDLE) mutex.mState;
583 nsecs_t absTime = systemTime()+reltime;
584
585 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800586}
587
588/*
589 * Signal the condition variable, allowing one thread to continue.
590 */
591void Condition::signal()
592{
593 WinCondition* condState = (WinCondition*) mState;
594
595 // Lock the internal mutex. This ensures that we don't clash with
596 // broadcast().
597 WaitForSingleObject(condState->internalMutex, INFINITE);
598
599 EnterCriticalSection(&condState->waitersCountLock);
600 bool haveWaiters = (condState->waitersCount > 0);
601 LeaveCriticalSection(&condState->waitersCountLock);
602
603 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
604 // down a notch.
605 if (haveWaiters)
606 ReleaseSemaphore(condState->sema, 1, 0);
607
608 // Release internal mutex.
609 ReleaseMutex(condState->internalMutex);
610}
611
612/*
613 * Signal the condition variable, allowing all threads to continue.
614 *
615 * First we have to wake up all threads waiting on the semaphore, then
616 * we wait until all of the threads have actually been woken before
617 * releasing the internal mutex. This ensures that all threads are woken.
618 */
619void Condition::broadcast()
620{
621 WinCondition* condState = (WinCondition*) mState;
622
623 // Lock the internal mutex. This keeps the guys we're waking up
624 // from getting too far.
625 WaitForSingleObject(condState->internalMutex, INFINITE);
626
627 EnterCriticalSection(&condState->waitersCountLock);
628 bool haveWaiters = false;
629
630 if (condState->waitersCount > 0) {
631 haveWaiters = true;
632 condState->wasBroadcast = true;
633 }
634
635 if (haveWaiters) {
636 // Wake up all the waiters.
637 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
638
639 LeaveCriticalSection(&condState->waitersCountLock);
640
641 // Wait for all awakened threads to acquire the counting semaphore.
642 // The last guy who was waiting sets this.
643 WaitForSingleObject(condState->waitersDone, INFINITE);
644
645 // Reset wasBroadcast. (No crit section needed because nobody
646 // else can wake up to poke at it.)
647 condState->wasBroadcast = 0;
648 } else {
649 // nothing to do
650 LeaveCriticalSection(&condState->waitersCountLock);
651 }
652
653 // Release internal mutex.
654 ReleaseMutex(condState->internalMutex);
655}
656
657#else
658#error "condition variables not supported on this platform"
659#endif
660
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800661// ----------------------------------------------------------------------------
662
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800663/*
664 * This is our thread object!
665 */
666
667Thread::Thread(bool canCallJava)
668 : mCanCallJava(canCallJava),
669 mThread(thread_id_t(-1)),
670 mLock("Thread::mLock"),
671 mStatus(NO_ERROR),
672 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800673#ifdef HAVE_ANDROID_OS
674 , mTid(-1)
675#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800676{
677}
678
679Thread::~Thread()
680{
681}
682
683status_t Thread::readyToRun()
684{
685 return NO_ERROR;
686}
687
688status_t Thread::run(const char* name, int32_t priority, size_t stack)
689{
690 Mutex::Autolock _l(mLock);
691
692 if (mRunning) {
693 // thread already started
694 return INVALID_OPERATION;
695 }
696
697 // reset status and exitPending to their default value, so we can
698 // try again after an error happened (either below, or in readyToRun())
699 mStatus = NO_ERROR;
700 mExitPending = false;
701 mThread = thread_id_t(-1);
702
703 // hold a strong reference on ourself
704 mHoldSelf = this;
705
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800706 mRunning = true;
707
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800708 bool res;
709 if (mCanCallJava) {
710 res = createThreadEtc(_threadLoop,
711 this, name, priority, stack, &mThread);
712 } else {
713 res = androidCreateRawThreadEtc(_threadLoop,
714 this, name, priority, stack, &mThread);
715 }
716
717 if (res == false) {
718 mStatus = UNKNOWN_ERROR; // something happened!
719 mRunning = false;
720 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800721 mHoldSelf.clear(); // "this" may have gone away after this.
722
723 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800724 }
725
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800726 // Do not refer to mStatus here: The thread is already running (may, in fact
727 // already have exited with a valid mStatus result). The NO_ERROR indication
728 // here merely indicates successfully starting the thread and does not
729 // imply successful termination/execution.
730 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800731
732 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800733}
734
735int Thread::_threadLoop(void* user)
736{
737 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800738
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800739 sp<Thread> strong(self->mHoldSelf);
740 wp<Thread> weak(strong);
741 self->mHoldSelf.clear();
742
Kenny Rootdafff0b2011-02-16 10:13:53 -0800743#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700744 // this is very useful for debugging with gdb
745 self->mTid = gettid();
746#endif
747
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800748 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800749
750 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800751 bool result;
752 if (first) {
753 first = false;
754 self->mStatus = self->readyToRun();
755 result = (self->mStatus == NO_ERROR);
756
Glenn Kasten966a48f2011-02-01 11:32:29 -0800757 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800758 // Binder threads (and maybe others) rely on threadLoop
759 // running at least once after a successful ::readyToRun()
760 // (unless, of course, the thread has already been asked to exit
761 // at that point).
762 // This is because threads are essentially used like this:
763 // (new ThreadSubclass())->run();
764 // The caller therefore does not retain a strong reference to
765 // the thread and the thread would simply disappear after the
766 // successful ::readyToRun() call instead of entering the
767 // threadLoop at least once.
768 result = self->threadLoop();
769 }
770 } else {
771 result = self->threadLoop();
772 }
773
Glenn Kasten966a48f2011-02-01 11:32:29 -0800774 // establish a scope for mLock
775 {
776 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800777 if (result == false || self->mExitPending) {
778 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800779 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800780 // clear thread ID so that requestExitAndWait() does not exit if
781 // called by a new thread using the same thread ID as this one.
782 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800783 // note that interested observers blocked in requestExitAndWait are
784 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700785 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800786 break;
787 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800788 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800789
790 // Release our strong reference, to let a chance to the thread
791 // to die a peaceful death.
792 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700793 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800794 strong = weak.promote();
795 } while(strong != 0);
796
797 return 0;
798}
799
800void Thread::requestExit()
801{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800802 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800803 mExitPending = true;
804}
805
806status_t Thread::requestExitAndWait()
807{
Glenn Kastena538e262011-06-02 08:59:28 -0700808 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800809 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000810 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800811 "Thread (this=%p): don't call waitForExit() from this "
812 "Thread object's thread. It's a guaranteed deadlock!",
813 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800814
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800815 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800816 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800817
Glenn Kastena538e262011-06-02 08:59:28 -0700818 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800819
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800820 while (mRunning == true) {
821 mThreadExitedCondition.wait(mLock);
822 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800823 // This next line is probably not needed any more, but is being left for
824 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800825 mExitPending = false;
826
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800827 return mStatus;
828}
829
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700830status_t Thread::join()
831{
832 Mutex::Autolock _l(mLock);
833 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000834 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700835 "Thread (this=%p): don't call join() from this "
836 "Thread object's thread. It's a guaranteed deadlock!",
837 this);
838
839 return WOULD_BLOCK;
840 }
841
842 while (mRunning == true) {
843 mThreadExitedCondition.wait(mLock);
844 }
845
846 return mStatus;
847}
848
Glenn Kastend731f072011-07-11 15:59:22 -0700849#ifdef HAVE_ANDROID_OS
850pid_t Thread::getTid() const
851{
852 // mTid is not defined until the child initializes it, and the caller may need it earlier
853 Mutex::Autolock _l(mLock);
854 pid_t tid;
855 if (mRunning) {
856 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
857 tid = __pthread_gettid(pthread);
858 } else {
859 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
860 tid = -1;
861 }
862 return tid;
863}
864#endif
865
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800866bool Thread::exitPending() const
867{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800868 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800869 return mExitPending;
870}
871
872
873
874}; // namespace android