blob: 38c4b35a7cfe31f4a1d9951930ea8938b9a0edc6 [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project7a4c8392009-03-05 14:34:35 -080017// #define LOG_NDEBUG 0
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080018#define LOG_TAG "libutils.threads"
19
20#include <utils/threads.h>
21#include <utils/Log.h>
22
Dianne Hackborn235af972009-12-07 17:59:37 -080023#include <cutils/sched_policy.h>
Dianne Hackborn16d217e2010-09-03 17:07:07 -070024#include <cutils/properties.h>
Dianne Hackborn235af972009-12-07 17:59:37 -080025
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080026#include <stdio.h>
27#include <stdlib.h>
28#include <memory.h>
29#include <errno.h>
30#include <assert.h>
31#include <unistd.h>
32
33#if defined(HAVE_PTHREADS)
34# include <pthread.h>
35# include <sched.h>
36# include <sys/resource.h>
37#elif defined(HAVE_WIN32_THREADS)
38# include <windows.h>
39# include <stdint.h>
40# include <process.h>
41# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
42#endif
43
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080044#if defined(HAVE_PRCTL)
45#include <sys/prctl.h>
46#endif
47
48/*
49 * ===========================================================================
50 * Thread wrappers
51 * ===========================================================================
52 */
53
54using namespace android;
55
56// ----------------------------------------------------------------------------
57#if defined(HAVE_PTHREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080058// ----------------------------------------------------------------------------
59
60/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070061 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080062 *
63 * We create it "detached", so it cleans up after itself.
64 */
65
66typedef void* (*android_pthread_entry)(void*);
67
Dianne Hackborna78bab02010-09-09 15:50:18 -070068static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
69static bool gDoSchedulingGroup = true;
70
71static void checkDoSchedulingGroup(void) {
72 char buf[PROPERTY_VALUE_MAX];
73 int len = property_get("debug.sys.noschedgroups", buf, "");
74 if (len > 0) {
75 int temp;
76 if (sscanf(buf, "%d", &temp) == 1) {
77 gDoSchedulingGroup = temp == 0;
78 }
79 }
80}
81
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080082struct thread_data_t {
83 thread_func_t entryFunction;
84 void* userData;
85 int priority;
86 char * threadName;
87
88 // we use this trampoline when we need to set the priority with
89 // nice/setpriority.
90 static int trampoline(const thread_data_t* t) {
91 thread_func_t f = t->entryFunction;
92 void* u = t->userData;
93 int prio = t->priority;
94 char * name = t->threadName;
95 delete t;
96 setpriority(PRIO_PROCESS, 0, prio);
Dianne Hackborna78bab02010-09-09 15:50:18 -070097 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
98 if (gDoSchedulingGroup) {
99 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
100 set_sched_policy(androidGetTid(), SP_BACKGROUND);
101 } else {
102 set_sched_policy(androidGetTid(), SP_FOREGROUND);
103 }
104 }
105
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800106 if (name) {
107#if defined(HAVE_PRCTL)
108 // Mac OS doesn't have this, and we build libutil for the host too
109 int hasAt = 0;
110 int hasDot = 0;
111 char *s = name;
112 while (*s) {
113 if (*s == '.') hasDot = 1;
114 else if (*s == '@') hasAt = 1;
115 s++;
116 }
117 int len = s - name;
118 if (len < 15 || hasAt || !hasDot) {
119 s = name;
120 } else {
121 s = name + len - 15;
122 }
123 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
124#endif
125 free(name);
126 }
127 return f(u);
128 }
129};
130
131int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
132 void *userData,
133 const char* threadName,
134 int32_t threadPriority,
135 size_t threadStackSize,
136 android_thread_id_t *threadId)
137{
138 pthread_attr_t attr;
139 pthread_attr_init(&attr);
140 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
141
142#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
143 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
144 // We could avoid the trampoline if there was a way to get to the
145 // android_thread_id_t (pid) from pthread_t
146 thread_data_t* t = new thread_data_t;
147 t->priority = threadPriority;
148 t->threadName = threadName ? strdup(threadName) : NULL;
149 t->entryFunction = entryFunction;
150 t->userData = userData;
151 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
152 userData = t;
153 }
154#endif
155
156 if (threadStackSize) {
157 pthread_attr_setstacksize(&attr, threadStackSize);
158 }
159
160 errno = 0;
161 pthread_t thread;
162 int result = pthread_create(&thread, &attr,
163 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700164 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800165 if (result != 0) {
166 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
167 "(android threadPriority=%d)",
168 entryFunction, result, errno, threadPriority);
169 return 0;
170 }
171
Glenn Kastena538e262011-06-02 08:59:28 -0700172 // Note that *threadID is directly available to the parent only, as it is
173 // assigned after the child starts. Use memory barrier / lock if the child
174 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800175 if (threadId != NULL) {
176 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
177 }
178 return 1;
179}
180
181android_thread_id_t androidGetThreadId()
182{
183 return (android_thread_id_t)pthread_self();
184}
185
186// ----------------------------------------------------------------------------
187#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800188// ----------------------------------------------------------------------------
189
190/*
191 * Trampoline to make us __stdcall-compliant.
192 *
193 * We're expected to delete "vDetails" when we're done.
194 */
195struct threadDetails {
196 int (*func)(void*);
197 void* arg;
198};
199static __stdcall unsigned int threadIntermediary(void* vDetails)
200{
201 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
202 int result;
203
204 result = (*(pDetails->func))(pDetails->arg);
205
206 delete pDetails;
207
208 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
209 return (unsigned int) result;
210}
211
212/*
213 * Create and run a new thread.
214 */
215static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
216{
217 HANDLE hThread;
218 struct threadDetails* pDetails = new threadDetails; // must be on heap
219 unsigned int thrdaddr;
220
221 pDetails->func = fn;
222 pDetails->arg = arg;
223
224#if defined(HAVE__BEGINTHREADEX)
225 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
226 &thrdaddr);
227 if (hThread == 0)
228#elif defined(HAVE_CREATETHREAD)
229 hThread = CreateThread(NULL, 0,
230 (LPTHREAD_START_ROUTINE) threadIntermediary,
231 (void*) pDetails, 0, (DWORD*) &thrdaddr);
232 if (hThread == NULL)
233#endif
234 {
235 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
236 return false;
237 }
238
239#if defined(HAVE_CREATETHREAD)
240 /* close the management handle */
241 CloseHandle(hThread);
242#endif
243
244 if (id != NULL) {
245 *id = (android_thread_id_t)thrdaddr;
246 }
247
248 return true;
249}
250
251int androidCreateRawThreadEtc(android_thread_func_t fn,
252 void *userData,
253 const char* threadName,
254 int32_t threadPriority,
255 size_t threadStackSize,
256 android_thread_id_t *threadId)
257{
258 return doCreateThread( fn, userData, threadId);
259}
260
261android_thread_id_t androidGetThreadId()
262{
263 return (android_thread_id_t)GetCurrentThreadId();
264}
265
266// ----------------------------------------------------------------------------
267#else
268#error "Threads not supported"
269#endif
270
271// ----------------------------------------------------------------------------
272
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800273int androidCreateThread(android_thread_func_t fn, void* arg)
274{
275 return createThreadEtc(fn, arg);
276}
277
278int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
279{
280 return createThreadEtc(fn, arg, "android:unnamed_thread",
281 PRIORITY_DEFAULT, 0, id);
282}
283
284static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
285
286int androidCreateThreadEtc(android_thread_func_t entryFunction,
287 void *userData,
288 const char* threadName,
289 int32_t threadPriority,
290 size_t threadStackSize,
291 android_thread_id_t *threadId)
292{
293 return gCreateThreadFn(entryFunction, userData, threadName,
294 threadPriority, threadStackSize, threadId);
295}
296
297void androidSetCreateThreadFunc(android_create_thread_fn func)
298{
299 gCreateThreadFn = func;
300}
301
Dianne Hackborn235af972009-12-07 17:59:37 -0800302pid_t androidGetTid()
303{
304#ifdef HAVE_GETTID
305 return gettid();
306#else
307 return getpid();
308#endif
309}
310
311int androidSetThreadSchedulingGroup(pid_t tid, int grp)
312{
313 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
314 return BAD_VALUE;
315 }
316
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800317#if defined(HAVE_PTHREADS)
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700318 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
319 if (gDoSchedulingGroup) {
Glenn Kasten5e0243f2011-06-22 17:42:23 -0700320 // set_sched_policy does not support tid == 0
321 if (tid == 0) {
322 tid = androidGetTid();
323 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700324 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
325 SP_BACKGROUND : SP_FOREGROUND)) {
326 return PERMISSION_DENIED;
327 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800328 }
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800329#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800330
331 return NO_ERROR;
332}
333
334int androidSetThreadPriority(pid_t tid, int pri)
335{
336 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800337
338#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800339 int lasterr = 0;
340
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700341 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
342 if (gDoSchedulingGroup) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700343 // set_sched_policy does not support tid == 0
344 int policy_tid;
345 if (tid == 0) {
346 policy_tid = androidGetTid();
347 } else {
348 policy_tid = tid;
349 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700350 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700351 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700352 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700353 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700354 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800355 }
356
357 if (rc) {
358 lasterr = errno;
359 }
360
361 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
362 rc = INVALID_OPERATION;
363 } else {
364 errno = lasterr;
365 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800366#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800367
368 return rc;
369}
370
Andreas Huber8ddbed92011-09-15 12:21:40 -0700371int androidGetThreadPriority(pid_t tid) {
372 return getpriority(PRIO_PROCESS, tid);
373}
374
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700375int androidGetThreadSchedulingGroup(pid_t tid)
376{
377 int ret = ANDROID_TGROUP_DEFAULT;
378
379#if defined(HAVE_PTHREADS)
380 // convention is to not call get/set_sched_policy methods if disabled by property
381 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
382 if (gDoSchedulingGroup) {
383 SchedPolicy policy;
384 // get_sched_policy does not support tid == 0
385 if (tid == 0) {
386 tid = androidGetTid();
387 }
388 if (get_sched_policy(tid, &policy) < 0) {
389 ret = INVALID_OPERATION;
390 } else {
391 switch (policy) {
392 case SP_BACKGROUND:
393 ret = ANDROID_TGROUP_BG_NONINTERACT;
394 break;
395 case SP_FOREGROUND:
396 ret = ANDROID_TGROUP_FG_BOOST;
397 break;
398 default:
399 // should not happen, as enum SchedPolicy does not have any other values
400 ret = INVALID_OPERATION;
401 break;
402 }
403 }
404 }
405#endif
406
407 return ret;
408}
409
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800410namespace android {
411
412/*
413 * ===========================================================================
414 * Mutex class
415 * ===========================================================================
416 */
417
Mathias Agopian15554362009-07-12 23:11:20 -0700418#if defined(HAVE_PTHREADS)
419// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800420#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800421
422Mutex::Mutex()
423{
424 HANDLE hMutex;
425
426 assert(sizeof(hMutex) == sizeof(mState));
427
428 hMutex = CreateMutex(NULL, FALSE, NULL);
429 mState = (void*) hMutex;
430}
431
432Mutex::Mutex(const char* name)
433{
434 // XXX: name not used for now
435 HANDLE hMutex;
436
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200437 assert(sizeof(hMutex) == sizeof(mState));
438
439 hMutex = CreateMutex(NULL, FALSE, NULL);
440 mState = (void*) hMutex;
441}
442
443Mutex::Mutex(int type, const char* name)
444{
445 // XXX: type and name not used for now
446 HANDLE hMutex;
447
448 assert(sizeof(hMutex) == sizeof(mState));
449
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800450 hMutex = CreateMutex(NULL, FALSE, NULL);
451 mState = (void*) hMutex;
452}
453
454Mutex::~Mutex()
455{
456 CloseHandle((HANDLE) mState);
457}
458
459status_t Mutex::lock()
460{
461 DWORD dwWaitResult;
462 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
463 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
464}
465
466void Mutex::unlock()
467{
468 if (!ReleaseMutex((HANDLE) mState))
469 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
470}
471
472status_t Mutex::tryLock()
473{
474 DWORD dwWaitResult;
475
476 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
477 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
478 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
479 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
480}
481
482#else
483#error "Somebody forgot to implement threads for this platform."
484#endif
485
486
487/*
488 * ===========================================================================
489 * Condition class
490 * ===========================================================================
491 */
492
Mathias Agopian15554362009-07-12 23:11:20 -0700493#if defined(HAVE_PTHREADS)
494// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800495#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800496
497/*
498 * Windows doesn't have a condition variable solution. It's possible
499 * to create one, but it's easy to get it wrong. For a discussion, and
500 * the origin of this implementation, see:
501 *
502 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
503 *
504 * The implementation shown on the page does NOT follow POSIX semantics.
505 * As an optimization they require acquiring the external mutex before
506 * calling signal() and broadcast(), whereas POSIX only requires grabbing
507 * it before calling wait(). The implementation here has been un-optimized
508 * to have the correct behavior.
509 */
510typedef struct WinCondition {
511 // Number of waiting threads.
512 int waitersCount;
513
514 // Serialize access to waitersCount.
515 CRITICAL_SECTION waitersCountLock;
516
517 // Semaphore used to queue up threads waiting for the condition to
518 // become signaled.
519 HANDLE sema;
520
521 // An auto-reset event used by the broadcast/signal thread to wait
522 // for all the waiting thread(s) to wake up and be released from
523 // the semaphore.
524 HANDLE waitersDone;
525
526 // This mutex wouldn't be necessary if we required that the caller
527 // lock the external mutex before calling signal() and broadcast().
528 // I'm trying to mimic pthread semantics though.
529 HANDLE internalMutex;
530
531 // Keeps track of whether we were broadcasting or signaling. This
532 // allows us to optimize the code if we're just signaling.
533 bool wasBroadcast;
534
535 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
536 {
537 // Increment the wait count, avoiding race conditions.
538 EnterCriticalSection(&condState->waitersCountLock);
539 condState->waitersCount++;
540 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
541 // condState->waitersCount, getThreadId());
542 LeaveCriticalSection(&condState->waitersCountLock);
543
544 DWORD timeout = INFINITE;
545 if (abstime) {
546 nsecs_t reltime = *abstime - systemTime();
547 if (reltime < 0)
548 reltime = 0;
549 timeout = reltime/1000000;
550 }
551
552 // Atomically release the external mutex and wait on the semaphore.
553 DWORD res =
554 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
555
556 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
557
558 // Reacquire lock to avoid race conditions.
559 EnterCriticalSection(&condState->waitersCountLock);
560
561 // No longer waiting.
562 condState->waitersCount--;
563
564 // Check to see if we're the last waiter after a broadcast.
565 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
566
567 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
568 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
569
570 LeaveCriticalSection(&condState->waitersCountLock);
571
572 // If we're the last waiter thread during this particular broadcast
573 // then signal broadcast() that we're all awake. It'll drop the
574 // internal mutex.
575 if (lastWaiter) {
576 // Atomically signal the "waitersDone" event and wait until we
577 // can acquire the internal mutex. We want to do this in one step
578 // because it ensures that everybody is in the mutex FIFO before
579 // any thread has a chance to run. Without it, another thread
580 // could wake up, do work, and hop back in ahead of us.
581 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
582 INFINITE, FALSE);
583 } else {
584 // Grab the internal mutex.
585 WaitForSingleObject(condState->internalMutex, INFINITE);
586 }
587
588 // Release the internal and grab the external.
589 ReleaseMutex(condState->internalMutex);
590 WaitForSingleObject(hMutex, INFINITE);
591
592 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
593 }
594} WinCondition;
595
596/*
597 * Constructor. Set up the WinCondition stuff.
598 */
599Condition::Condition()
600{
601 WinCondition* condState = new WinCondition;
602
603 condState->waitersCount = 0;
604 condState->wasBroadcast = false;
605 // semaphore: no security, initial value of 0
606 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
607 InitializeCriticalSection(&condState->waitersCountLock);
608 // auto-reset event, not signaled initially
609 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
610 // used so we don't have to lock external mutex on signal/broadcast
611 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
612
613 mState = condState;
614}
615
616/*
617 * Destructor. Free Windows resources as well as our allocated storage.
618 */
619Condition::~Condition()
620{
621 WinCondition* condState = (WinCondition*) mState;
622 if (condState != NULL) {
623 CloseHandle(condState->sema);
624 CloseHandle(condState->waitersDone);
625 delete condState;
626 }
627}
628
629
630status_t Condition::wait(Mutex& mutex)
631{
632 WinCondition* condState = (WinCondition*) mState;
633 HANDLE hMutex = (HANDLE) mutex.mState;
634
635 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
636}
637
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800638status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
639{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200640 WinCondition* condState = (WinCondition*) mState;
641 HANDLE hMutex = (HANDLE) mutex.mState;
642 nsecs_t absTime = systemTime()+reltime;
643
644 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800645}
646
647/*
648 * Signal the condition variable, allowing one thread to continue.
649 */
650void Condition::signal()
651{
652 WinCondition* condState = (WinCondition*) mState;
653
654 // Lock the internal mutex. This ensures that we don't clash with
655 // broadcast().
656 WaitForSingleObject(condState->internalMutex, INFINITE);
657
658 EnterCriticalSection(&condState->waitersCountLock);
659 bool haveWaiters = (condState->waitersCount > 0);
660 LeaveCriticalSection(&condState->waitersCountLock);
661
662 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
663 // down a notch.
664 if (haveWaiters)
665 ReleaseSemaphore(condState->sema, 1, 0);
666
667 // Release internal mutex.
668 ReleaseMutex(condState->internalMutex);
669}
670
671/*
672 * Signal the condition variable, allowing all threads to continue.
673 *
674 * First we have to wake up all threads waiting on the semaphore, then
675 * we wait until all of the threads have actually been woken before
676 * releasing the internal mutex. This ensures that all threads are woken.
677 */
678void Condition::broadcast()
679{
680 WinCondition* condState = (WinCondition*) mState;
681
682 // Lock the internal mutex. This keeps the guys we're waking up
683 // from getting too far.
684 WaitForSingleObject(condState->internalMutex, INFINITE);
685
686 EnterCriticalSection(&condState->waitersCountLock);
687 bool haveWaiters = false;
688
689 if (condState->waitersCount > 0) {
690 haveWaiters = true;
691 condState->wasBroadcast = true;
692 }
693
694 if (haveWaiters) {
695 // Wake up all the waiters.
696 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
697
698 LeaveCriticalSection(&condState->waitersCountLock);
699
700 // Wait for all awakened threads to acquire the counting semaphore.
701 // The last guy who was waiting sets this.
702 WaitForSingleObject(condState->waitersDone, INFINITE);
703
704 // Reset wasBroadcast. (No crit section needed because nobody
705 // else can wake up to poke at it.)
706 condState->wasBroadcast = 0;
707 } else {
708 // nothing to do
709 LeaveCriticalSection(&condState->waitersCountLock);
710 }
711
712 // Release internal mutex.
713 ReleaseMutex(condState->internalMutex);
714}
715
716#else
717#error "condition variables not supported on this platform"
718#endif
719
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800720// ----------------------------------------------------------------------------
721
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800722/*
723 * This is our thread object!
724 */
725
726Thread::Thread(bool canCallJava)
727 : mCanCallJava(canCallJava),
728 mThread(thread_id_t(-1)),
729 mLock("Thread::mLock"),
730 mStatus(NO_ERROR),
731 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800732#ifdef HAVE_ANDROID_OS
733 , mTid(-1)
734#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800735{
736}
737
738Thread::~Thread()
739{
740}
741
742status_t Thread::readyToRun()
743{
744 return NO_ERROR;
745}
746
747status_t Thread::run(const char* name, int32_t priority, size_t stack)
748{
749 Mutex::Autolock _l(mLock);
750
751 if (mRunning) {
752 // thread already started
753 return INVALID_OPERATION;
754 }
755
756 // reset status and exitPending to their default value, so we can
757 // try again after an error happened (either below, or in readyToRun())
758 mStatus = NO_ERROR;
759 mExitPending = false;
760 mThread = thread_id_t(-1);
761
762 // hold a strong reference on ourself
763 mHoldSelf = this;
764
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800765 mRunning = true;
766
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800767 bool res;
768 if (mCanCallJava) {
769 res = createThreadEtc(_threadLoop,
770 this, name, priority, stack, &mThread);
771 } else {
772 res = androidCreateRawThreadEtc(_threadLoop,
773 this, name, priority, stack, &mThread);
774 }
775
776 if (res == false) {
777 mStatus = UNKNOWN_ERROR; // something happened!
778 mRunning = false;
779 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800780 mHoldSelf.clear(); // "this" may have gone away after this.
781
782 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800783 }
784
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800785 // Do not refer to mStatus here: The thread is already running (may, in fact
786 // already have exited with a valid mStatus result). The NO_ERROR indication
787 // here merely indicates successfully starting the thread and does not
788 // imply successful termination/execution.
789 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800790
791 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800792}
793
794int Thread::_threadLoop(void* user)
795{
796 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800797
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800798 sp<Thread> strong(self->mHoldSelf);
799 wp<Thread> weak(strong);
800 self->mHoldSelf.clear();
801
Kenny Rootdafff0b2011-02-16 10:13:53 -0800802#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700803 // this is very useful for debugging with gdb
804 self->mTid = gettid();
805#endif
806
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800807 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800808
809 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800810 bool result;
811 if (first) {
812 first = false;
813 self->mStatus = self->readyToRun();
814 result = (self->mStatus == NO_ERROR);
815
Glenn Kasten966a48f2011-02-01 11:32:29 -0800816 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800817 // Binder threads (and maybe others) rely on threadLoop
818 // running at least once after a successful ::readyToRun()
819 // (unless, of course, the thread has already been asked to exit
820 // at that point).
821 // This is because threads are essentially used like this:
822 // (new ThreadSubclass())->run();
823 // The caller therefore does not retain a strong reference to
824 // the thread and the thread would simply disappear after the
825 // successful ::readyToRun() call instead of entering the
826 // threadLoop at least once.
827 result = self->threadLoop();
828 }
829 } else {
830 result = self->threadLoop();
831 }
832
Glenn Kasten966a48f2011-02-01 11:32:29 -0800833 // establish a scope for mLock
834 {
835 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800836 if (result == false || self->mExitPending) {
837 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800838 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800839 // clear thread ID so that requestExitAndWait() does not exit if
840 // called by a new thread using the same thread ID as this one.
841 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800842 // note that interested observers blocked in requestExitAndWait are
843 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700844 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800845 break;
846 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800847 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800848
849 // Release our strong reference, to let a chance to the thread
850 // to die a peaceful death.
851 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700852 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800853 strong = weak.promote();
854 } while(strong != 0);
855
856 return 0;
857}
858
859void Thread::requestExit()
860{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800861 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800862 mExitPending = true;
863}
864
865status_t Thread::requestExitAndWait()
866{
Glenn Kastena538e262011-06-02 08:59:28 -0700867 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800868 if (mThread == getThreadId()) {
869 LOGW(
870 "Thread (this=%p): don't call waitForExit() from this "
871 "Thread object's thread. It's a guaranteed deadlock!",
872 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800873
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800874 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800875 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800876
Glenn Kastena538e262011-06-02 08:59:28 -0700877 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800878
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800879 while (mRunning == true) {
880 mThreadExitedCondition.wait(mLock);
881 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800882 // This next line is probably not needed any more, but is being left for
883 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800884 mExitPending = false;
885
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800886 return mStatus;
887}
888
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700889status_t Thread::join()
890{
891 Mutex::Autolock _l(mLock);
892 if (mThread == getThreadId()) {
893 LOGW(
894 "Thread (this=%p): don't call join() from this "
895 "Thread object's thread. It's a guaranteed deadlock!",
896 this);
897
898 return WOULD_BLOCK;
899 }
900
901 while (mRunning == true) {
902 mThreadExitedCondition.wait(mLock);
903 }
904
905 return mStatus;
906}
907
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800908bool Thread::exitPending() const
909{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800910 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800911 return mExitPending;
912}
913
914
915
916}; // namespace android