blob: a25a81fbeb062e935d4110104dc27fd1f3f239b5 [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
Dianne Hackborna78bab02010-09-09 15:50:18 -070071static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
72static bool gDoSchedulingGroup = true;
73
74static void checkDoSchedulingGroup(void) {
75 char buf[PROPERTY_VALUE_MAX];
76 int len = property_get("debug.sys.noschedgroups", buf, "");
77 if (len > 0) {
78 int temp;
79 if (sscanf(buf, "%d", &temp) == 1) {
80 gDoSchedulingGroup = temp == 0;
81 }
82 }
83}
84
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080085struct thread_data_t {
86 thread_func_t entryFunction;
87 void* userData;
88 int priority;
89 char * threadName;
90
91 // we use this trampoline when we need to set the priority with
Glenn Kastend731f072011-07-11 15:59:22 -070092 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080093 static int trampoline(const thread_data_t* t) {
94 thread_func_t f = t->entryFunction;
95 void* u = t->userData;
96 int prio = t->priority;
97 char * name = t->threadName;
98 delete t;
99 setpriority(PRIO_PROCESS, 0, prio);
Dianne Hackborna78bab02010-09-09 15:50:18 -0700100 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
101 if (gDoSchedulingGroup) {
102 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
103 set_sched_policy(androidGetTid(), SP_BACKGROUND);
Glenn Kasten2b1d4992012-05-10 15:50:19 -0700104 } else if (prio > ANDROID_PRIORITY_AUDIO) {
Dianne Hackborna78bab02010-09-09 15:50:18 -0700105 set_sched_policy(androidGetTid(), SP_FOREGROUND);
Glenn Kasten2b1d4992012-05-10 15:50:19 -0700106 } else {
107 // defaults to that of parent, or as set by requestPriority()
Dianne Hackborna78bab02010-09-09 15:50:18 -0700108 }
109 }
110
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800111 if (name) {
112#if defined(HAVE_PRCTL)
113 // Mac OS doesn't have this, and we build libutil for the host too
114 int hasAt = 0;
115 int hasDot = 0;
116 char *s = name;
117 while (*s) {
118 if (*s == '.') hasDot = 1;
119 else if (*s == '@') hasAt = 1;
120 s++;
121 }
122 int len = s - name;
123 if (len < 15 || hasAt || !hasDot) {
124 s = name;
125 } else {
126 s = name + len - 15;
127 }
128 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
129#endif
130 free(name);
131 }
132 return f(u);
133 }
134};
135
136int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
137 void *userData,
138 const char* threadName,
139 int32_t threadPriority,
140 size_t threadStackSize,
141 android_thread_id_t *threadId)
142{
143 pthread_attr_t attr;
144 pthread_attr_init(&attr);
145 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
146
147#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
148 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700149 // Now that the pthread_t has a method to find the associated
150 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
151 // this trampoline in some cases as the parent could set the properties
152 // for the child. However, there would be a race condition because the
153 // child becomes ready immediately, and it doesn't work for the name.
154 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
155 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800156 thread_data_t* t = new thread_data_t;
157 t->priority = threadPriority;
158 t->threadName = threadName ? strdup(threadName) : NULL;
159 t->entryFunction = entryFunction;
160 t->userData = userData;
161 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
162 userData = t;
163 }
164#endif
165
166 if (threadStackSize) {
167 pthread_attr_setstacksize(&attr, threadStackSize);
168 }
169
170 errno = 0;
171 pthread_t thread;
172 int result = pthread_create(&thread, &attr,
173 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700174 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800175 if (result != 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000176 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800177 "(android threadPriority=%d)",
178 entryFunction, result, errno, threadPriority);
179 return 0;
180 }
181
Glenn Kastena538e262011-06-02 08:59:28 -0700182 // Note that *threadID is directly available to the parent only, as it is
183 // assigned after the child starts. Use memory barrier / lock if the child
184 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800185 if (threadId != NULL) {
186 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
187 }
188 return 1;
189}
190
Glenn Kastend731f072011-07-11 15:59:22 -0700191#ifdef HAVE_ANDROID_OS
192static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
193{
194 return (pthread_t) thread;
195}
196#endif
197
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800198android_thread_id_t androidGetThreadId()
199{
200 return (android_thread_id_t)pthread_self();
201}
202
203// ----------------------------------------------------------------------------
204#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800205// ----------------------------------------------------------------------------
206
207/*
208 * Trampoline to make us __stdcall-compliant.
209 *
210 * We're expected to delete "vDetails" when we're done.
211 */
212struct threadDetails {
213 int (*func)(void*);
214 void* arg;
215};
216static __stdcall unsigned int threadIntermediary(void* vDetails)
217{
218 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
219 int result;
220
221 result = (*(pDetails->func))(pDetails->arg);
222
223 delete pDetails;
224
Steve Block8b4cf772011-10-12 17:27:03 +0100225 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800226 return (unsigned int) result;
227}
228
229/*
230 * Create and run a new thread.
231 */
232static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
233{
234 HANDLE hThread;
235 struct threadDetails* pDetails = new threadDetails; // must be on heap
236 unsigned int thrdaddr;
237
238 pDetails->func = fn;
239 pDetails->arg = arg;
240
241#if defined(HAVE__BEGINTHREADEX)
242 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
243 &thrdaddr);
244 if (hThread == 0)
245#elif defined(HAVE_CREATETHREAD)
246 hThread = CreateThread(NULL, 0,
247 (LPTHREAD_START_ROUTINE) threadIntermediary,
248 (void*) pDetails, 0, (DWORD*) &thrdaddr);
249 if (hThread == NULL)
250#endif
251 {
Steve Block8b4cf772011-10-12 17:27:03 +0100252 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800253 return false;
254 }
255
256#if defined(HAVE_CREATETHREAD)
257 /* close the management handle */
258 CloseHandle(hThread);
259#endif
260
261 if (id != NULL) {
262 *id = (android_thread_id_t)thrdaddr;
263 }
264
265 return true;
266}
267
268int androidCreateRawThreadEtc(android_thread_func_t fn,
269 void *userData,
270 const char* threadName,
271 int32_t threadPriority,
272 size_t threadStackSize,
273 android_thread_id_t *threadId)
274{
275 return doCreateThread( fn, userData, threadId);
276}
277
278android_thread_id_t androidGetThreadId()
279{
280 return (android_thread_id_t)GetCurrentThreadId();
281}
282
283// ----------------------------------------------------------------------------
284#else
285#error "Threads not supported"
286#endif
287
288// ----------------------------------------------------------------------------
289
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800290int androidCreateThread(android_thread_func_t fn, void* arg)
291{
292 return createThreadEtc(fn, arg);
293}
294
295int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
296{
297 return createThreadEtc(fn, arg, "android:unnamed_thread",
298 PRIORITY_DEFAULT, 0, id);
299}
300
301static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
302
303int androidCreateThreadEtc(android_thread_func_t entryFunction,
304 void *userData,
305 const char* threadName,
306 int32_t threadPriority,
307 size_t threadStackSize,
308 android_thread_id_t *threadId)
309{
310 return gCreateThreadFn(entryFunction, userData, threadName,
311 threadPriority, threadStackSize, threadId);
312}
313
314void androidSetCreateThreadFunc(android_create_thread_fn func)
315{
316 gCreateThreadFn = func;
317}
318
Dianne Hackborn235af972009-12-07 17:59:37 -0800319pid_t androidGetTid()
320{
321#ifdef HAVE_GETTID
322 return gettid();
323#else
324 return getpid();
325#endif
326}
327
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700328#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800329int androidSetThreadPriority(pid_t tid, int pri)
330{
331 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800332
333#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800334 int lasterr = 0;
335
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700336 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
337 if (gDoSchedulingGroup) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700338 // set_sched_policy does not support tid == 0
339 int policy_tid;
340 if (tid == 0) {
341 policy_tid = androidGetTid();
342 } else {
343 policy_tid = tid;
344 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700345 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700346 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700347 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700348 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700349 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800350 }
351
352 if (rc) {
353 lasterr = errno;
354 }
355
356 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
357 rc = INVALID_OPERATION;
358 } else {
359 errno = lasterr;
360 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800361#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800362
363 return rc;
364}
365
Andreas Huber8ddbed92011-09-15 12:21:40 -0700366int androidGetThreadPriority(pid_t tid) {
Andreas Huber7b4ce612011-09-16 11:47:13 -0700367#if defined(HAVE_PTHREADS)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700368 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700369#else
370 return ANDROID_PRIORITY_NORMAL;
371#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700372}
373
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700374#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700375
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800376namespace android {
377
378/*
379 * ===========================================================================
380 * Mutex class
381 * ===========================================================================
382 */
383
Mathias Agopian15554362009-07-12 23:11:20 -0700384#if defined(HAVE_PTHREADS)
385// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800386#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800387
388Mutex::Mutex()
389{
390 HANDLE hMutex;
391
392 assert(sizeof(hMutex) == sizeof(mState));
393
394 hMutex = CreateMutex(NULL, FALSE, NULL);
395 mState = (void*) hMutex;
396}
397
398Mutex::Mutex(const char* name)
399{
400 // XXX: name not used for now
401 HANDLE hMutex;
402
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200403 assert(sizeof(hMutex) == sizeof(mState));
404
405 hMutex = CreateMutex(NULL, FALSE, NULL);
406 mState = (void*) hMutex;
407}
408
409Mutex::Mutex(int type, const char* name)
410{
411 // XXX: type and name not used for now
412 HANDLE hMutex;
413
414 assert(sizeof(hMutex) == sizeof(mState));
415
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800416 hMutex = CreateMutex(NULL, FALSE, NULL);
417 mState = (void*) hMutex;
418}
419
420Mutex::~Mutex()
421{
422 CloseHandle((HANDLE) mState);
423}
424
425status_t Mutex::lock()
426{
427 DWORD dwWaitResult;
428 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
429 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
430}
431
432void Mutex::unlock()
433{
434 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100435 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800436}
437
438status_t Mutex::tryLock()
439{
440 DWORD dwWaitResult;
441
442 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
443 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100444 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800445 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
446}
447
448#else
449#error "Somebody forgot to implement threads for this platform."
450#endif
451
452
453/*
454 * ===========================================================================
455 * Condition class
456 * ===========================================================================
457 */
458
Mathias Agopian15554362009-07-12 23:11:20 -0700459#if defined(HAVE_PTHREADS)
460// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800461#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462
463/*
464 * Windows doesn't have a condition variable solution. It's possible
465 * to create one, but it's easy to get it wrong. For a discussion, and
466 * the origin of this implementation, see:
467 *
468 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
469 *
470 * The implementation shown on the page does NOT follow POSIX semantics.
471 * As an optimization they require acquiring the external mutex before
472 * calling signal() and broadcast(), whereas POSIX only requires grabbing
473 * it before calling wait(). The implementation here has been un-optimized
474 * to have the correct behavior.
475 */
476typedef struct WinCondition {
477 // Number of waiting threads.
478 int waitersCount;
479
480 // Serialize access to waitersCount.
481 CRITICAL_SECTION waitersCountLock;
482
483 // Semaphore used to queue up threads waiting for the condition to
484 // become signaled.
485 HANDLE sema;
486
487 // An auto-reset event used by the broadcast/signal thread to wait
488 // for all the waiting thread(s) to wake up and be released from
489 // the semaphore.
490 HANDLE waitersDone;
491
492 // This mutex wouldn't be necessary if we required that the caller
493 // lock the external mutex before calling signal() and broadcast().
494 // I'm trying to mimic pthread semantics though.
495 HANDLE internalMutex;
496
497 // Keeps track of whether we were broadcasting or signaling. This
498 // allows us to optimize the code if we're just signaling.
499 bool wasBroadcast;
500
501 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
502 {
503 // Increment the wait count, avoiding race conditions.
504 EnterCriticalSection(&condState->waitersCountLock);
505 condState->waitersCount++;
506 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
507 // condState->waitersCount, getThreadId());
508 LeaveCriticalSection(&condState->waitersCountLock);
509
510 DWORD timeout = INFINITE;
511 if (abstime) {
512 nsecs_t reltime = *abstime - systemTime();
513 if (reltime < 0)
514 reltime = 0;
515 timeout = reltime/1000000;
516 }
517
518 // Atomically release the external mutex and wait on the semaphore.
519 DWORD res =
520 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
521
522 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
523
524 // Reacquire lock to avoid race conditions.
525 EnterCriticalSection(&condState->waitersCountLock);
526
527 // No longer waiting.
528 condState->waitersCount--;
529
530 // Check to see if we're the last waiter after a broadcast.
531 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
532
533 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
534 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
535
536 LeaveCriticalSection(&condState->waitersCountLock);
537
538 // If we're the last waiter thread during this particular broadcast
539 // then signal broadcast() that we're all awake. It'll drop the
540 // internal mutex.
541 if (lastWaiter) {
542 // Atomically signal the "waitersDone" event and wait until we
543 // can acquire the internal mutex. We want to do this in one step
544 // because it ensures that everybody is in the mutex FIFO before
545 // any thread has a chance to run. Without it, another thread
546 // could wake up, do work, and hop back in ahead of us.
547 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
548 INFINITE, FALSE);
549 } else {
550 // Grab the internal mutex.
551 WaitForSingleObject(condState->internalMutex, INFINITE);
552 }
553
554 // Release the internal and grab the external.
555 ReleaseMutex(condState->internalMutex);
556 WaitForSingleObject(hMutex, INFINITE);
557
558 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
559 }
560} WinCondition;
561
562/*
563 * Constructor. Set up the WinCondition stuff.
564 */
565Condition::Condition()
566{
567 WinCondition* condState = new WinCondition;
568
569 condState->waitersCount = 0;
570 condState->wasBroadcast = false;
571 // semaphore: no security, initial value of 0
572 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
573 InitializeCriticalSection(&condState->waitersCountLock);
574 // auto-reset event, not signaled initially
575 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
576 // used so we don't have to lock external mutex on signal/broadcast
577 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
578
579 mState = condState;
580}
581
582/*
583 * Destructor. Free Windows resources as well as our allocated storage.
584 */
585Condition::~Condition()
586{
587 WinCondition* condState = (WinCondition*) mState;
588 if (condState != NULL) {
589 CloseHandle(condState->sema);
590 CloseHandle(condState->waitersDone);
591 delete condState;
592 }
593}
594
595
596status_t Condition::wait(Mutex& mutex)
597{
598 WinCondition* condState = (WinCondition*) mState;
599 HANDLE hMutex = (HANDLE) mutex.mState;
600
601 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
602}
603
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800604status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
605{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200606 WinCondition* condState = (WinCondition*) mState;
607 HANDLE hMutex = (HANDLE) mutex.mState;
608 nsecs_t absTime = systemTime()+reltime;
609
610 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800611}
612
613/*
614 * Signal the condition variable, allowing one thread to continue.
615 */
616void Condition::signal()
617{
618 WinCondition* condState = (WinCondition*) mState;
619
620 // Lock the internal mutex. This ensures that we don't clash with
621 // broadcast().
622 WaitForSingleObject(condState->internalMutex, INFINITE);
623
624 EnterCriticalSection(&condState->waitersCountLock);
625 bool haveWaiters = (condState->waitersCount > 0);
626 LeaveCriticalSection(&condState->waitersCountLock);
627
628 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
629 // down a notch.
630 if (haveWaiters)
631 ReleaseSemaphore(condState->sema, 1, 0);
632
633 // Release internal mutex.
634 ReleaseMutex(condState->internalMutex);
635}
636
637/*
638 * Signal the condition variable, allowing all threads to continue.
639 *
640 * First we have to wake up all threads waiting on the semaphore, then
641 * we wait until all of the threads have actually been woken before
642 * releasing the internal mutex. This ensures that all threads are woken.
643 */
644void Condition::broadcast()
645{
646 WinCondition* condState = (WinCondition*) mState;
647
648 // Lock the internal mutex. This keeps the guys we're waking up
649 // from getting too far.
650 WaitForSingleObject(condState->internalMutex, INFINITE);
651
652 EnterCriticalSection(&condState->waitersCountLock);
653 bool haveWaiters = false;
654
655 if (condState->waitersCount > 0) {
656 haveWaiters = true;
657 condState->wasBroadcast = true;
658 }
659
660 if (haveWaiters) {
661 // Wake up all the waiters.
662 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
663
664 LeaveCriticalSection(&condState->waitersCountLock);
665
666 // Wait for all awakened threads to acquire the counting semaphore.
667 // The last guy who was waiting sets this.
668 WaitForSingleObject(condState->waitersDone, INFINITE);
669
670 // Reset wasBroadcast. (No crit section needed because nobody
671 // else can wake up to poke at it.)
672 condState->wasBroadcast = 0;
673 } else {
674 // nothing to do
675 LeaveCriticalSection(&condState->waitersCountLock);
676 }
677
678 // Release internal mutex.
679 ReleaseMutex(condState->internalMutex);
680}
681
682#else
683#error "condition variables not supported on this platform"
684#endif
685
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800686// ----------------------------------------------------------------------------
687
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800688/*
689 * This is our thread object!
690 */
691
692Thread::Thread(bool canCallJava)
693 : mCanCallJava(canCallJava),
694 mThread(thread_id_t(-1)),
695 mLock("Thread::mLock"),
696 mStatus(NO_ERROR),
697 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800698#ifdef HAVE_ANDROID_OS
699 , mTid(-1)
700#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800701{
702}
703
704Thread::~Thread()
705{
706}
707
708status_t Thread::readyToRun()
709{
710 return NO_ERROR;
711}
712
713status_t Thread::run(const char* name, int32_t priority, size_t stack)
714{
715 Mutex::Autolock _l(mLock);
716
717 if (mRunning) {
718 // thread already started
719 return INVALID_OPERATION;
720 }
721
722 // reset status and exitPending to their default value, so we can
723 // try again after an error happened (either below, or in readyToRun())
724 mStatus = NO_ERROR;
725 mExitPending = false;
726 mThread = thread_id_t(-1);
727
728 // hold a strong reference on ourself
729 mHoldSelf = this;
730
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800731 mRunning = true;
732
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800733 bool res;
734 if (mCanCallJava) {
735 res = createThreadEtc(_threadLoop,
736 this, name, priority, stack, &mThread);
737 } else {
738 res = androidCreateRawThreadEtc(_threadLoop,
739 this, name, priority, stack, &mThread);
740 }
741
742 if (res == false) {
743 mStatus = UNKNOWN_ERROR; // something happened!
744 mRunning = false;
745 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800746 mHoldSelf.clear(); // "this" may have gone away after this.
747
748 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800749 }
750
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800751 // Do not refer to mStatus here: The thread is already running (may, in fact
752 // already have exited with a valid mStatus result). The NO_ERROR indication
753 // here merely indicates successfully starting the thread and does not
754 // imply successful termination/execution.
755 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800756
757 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800758}
759
760int Thread::_threadLoop(void* user)
761{
762 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800763
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800764 sp<Thread> strong(self->mHoldSelf);
765 wp<Thread> weak(strong);
766 self->mHoldSelf.clear();
767
Kenny Rootdafff0b2011-02-16 10:13:53 -0800768#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700769 // this is very useful for debugging with gdb
770 self->mTid = gettid();
771#endif
772
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800773 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800774
775 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800776 bool result;
777 if (first) {
778 first = false;
779 self->mStatus = self->readyToRun();
780 result = (self->mStatus == NO_ERROR);
781
Glenn Kasten966a48f2011-02-01 11:32:29 -0800782 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800783 // Binder threads (and maybe others) rely on threadLoop
784 // running at least once after a successful ::readyToRun()
785 // (unless, of course, the thread has already been asked to exit
786 // at that point).
787 // This is because threads are essentially used like this:
788 // (new ThreadSubclass())->run();
789 // The caller therefore does not retain a strong reference to
790 // the thread and the thread would simply disappear after the
791 // successful ::readyToRun() call instead of entering the
792 // threadLoop at least once.
793 result = self->threadLoop();
794 }
795 } else {
796 result = self->threadLoop();
797 }
798
Glenn Kasten966a48f2011-02-01 11:32:29 -0800799 // establish a scope for mLock
800 {
801 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800802 if (result == false || self->mExitPending) {
803 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800804 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800805 // clear thread ID so that requestExitAndWait() does not exit if
806 // called by a new thread using the same thread ID as this one.
807 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800808 // note that interested observers blocked in requestExitAndWait are
809 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700810 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800811 break;
812 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800813 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800814
815 // Release our strong reference, to let a chance to the thread
816 // to die a peaceful death.
817 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700818 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800819 strong = weak.promote();
820 } while(strong != 0);
821
822 return 0;
823}
824
825void Thread::requestExit()
826{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800827 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800828 mExitPending = true;
829}
830
831status_t Thread::requestExitAndWait()
832{
Glenn Kastena538e262011-06-02 08:59:28 -0700833 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800834 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000835 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800836 "Thread (this=%p): don't call waitForExit() from this "
837 "Thread object's thread. It's a guaranteed deadlock!",
838 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800839
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800840 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800841 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800842
Glenn Kastena538e262011-06-02 08:59:28 -0700843 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800844
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800845 while (mRunning == true) {
846 mThreadExitedCondition.wait(mLock);
847 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800848 // This next line is probably not needed any more, but is being left for
849 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800850 mExitPending = false;
851
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800852 return mStatus;
853}
854
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700855status_t Thread::join()
856{
857 Mutex::Autolock _l(mLock);
858 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000859 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700860 "Thread (this=%p): don't call join() from this "
861 "Thread object's thread. It's a guaranteed deadlock!",
862 this);
863
864 return WOULD_BLOCK;
865 }
866
867 while (mRunning == true) {
868 mThreadExitedCondition.wait(mLock);
869 }
870
871 return mStatus;
872}
873
Glenn Kastend731f072011-07-11 15:59:22 -0700874#ifdef HAVE_ANDROID_OS
875pid_t Thread::getTid() const
876{
877 // mTid is not defined until the child initializes it, and the caller may need it earlier
878 Mutex::Autolock _l(mLock);
879 pid_t tid;
880 if (mRunning) {
881 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
882 tid = __pthread_gettid(pthread);
883 } else {
884 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
885 tid = -1;
886 }
887 return tid;
888}
889#endif
890
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800891bool Thread::exitPending() const
892{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800893 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800894 return mExitPending;
895}
896
897
898
899}; // namespace android