blob: ab207f5655c5074b825f1bd21df0ef3cf5e9330e [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);
104 } else {
105 set_sched_policy(androidGetTid(), SP_FOREGROUND);
106 }
107 }
108
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800109 if (name) {
110#if defined(HAVE_PRCTL)
111 // Mac OS doesn't have this, and we build libutil for the host too
112 int hasAt = 0;
113 int hasDot = 0;
114 char *s = name;
115 while (*s) {
116 if (*s == '.') hasDot = 1;
117 else if (*s == '@') hasAt = 1;
118 s++;
119 }
120 int len = s - name;
121 if (len < 15 || hasAt || !hasDot) {
122 s = name;
123 } else {
124 s = name + len - 15;
125 }
126 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
127#endif
128 free(name);
129 }
130 return f(u);
131 }
132};
133
134int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
135 void *userData,
136 const char* threadName,
137 int32_t threadPriority,
138 size_t threadStackSize,
139 android_thread_id_t *threadId)
140{
141 pthread_attr_t attr;
142 pthread_attr_init(&attr);
143 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
144
145#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
146 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700147 // Now that the pthread_t has a method to find the associated
148 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
149 // this trampoline in some cases as the parent could set the properties
150 // for the child. However, there would be a race condition because the
151 // child becomes ready immediately, and it doesn't work for the name.
152 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
153 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800154 thread_data_t* t = new thread_data_t;
155 t->priority = threadPriority;
156 t->threadName = threadName ? strdup(threadName) : NULL;
157 t->entryFunction = entryFunction;
158 t->userData = userData;
159 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
160 userData = t;
161 }
162#endif
163
164 if (threadStackSize) {
165 pthread_attr_setstacksize(&attr, threadStackSize);
166 }
167
168 errno = 0;
169 pthread_t thread;
170 int result = pthread_create(&thread, &attr,
171 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700172 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800173 if (result != 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000174 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800175 "(android threadPriority=%d)",
176 entryFunction, result, errno, threadPriority);
177 return 0;
178 }
179
Glenn Kastena538e262011-06-02 08:59:28 -0700180 // Note that *threadID is directly available to the parent only, as it is
181 // assigned after the child starts. Use memory barrier / lock if the child
182 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800183 if (threadId != NULL) {
184 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
185 }
186 return 1;
187}
188
Glenn Kastend731f072011-07-11 15:59:22 -0700189#ifdef HAVE_ANDROID_OS
190static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
191{
192 return (pthread_t) thread;
193}
194#endif
195
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800196android_thread_id_t androidGetThreadId()
197{
198 return (android_thread_id_t)pthread_self();
199}
200
201// ----------------------------------------------------------------------------
202#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800203// ----------------------------------------------------------------------------
204
205/*
206 * Trampoline to make us __stdcall-compliant.
207 *
208 * We're expected to delete "vDetails" when we're done.
209 */
210struct threadDetails {
211 int (*func)(void*);
212 void* arg;
213};
214static __stdcall unsigned int threadIntermediary(void* vDetails)
215{
216 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
217 int result;
218
219 result = (*(pDetails->func))(pDetails->arg);
220
221 delete pDetails;
222
Steve Block8b4cf772011-10-12 17:27:03 +0100223 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800224 return (unsigned int) result;
225}
226
227/*
228 * Create and run a new thread.
229 */
230static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
231{
232 HANDLE hThread;
233 struct threadDetails* pDetails = new threadDetails; // must be on heap
234 unsigned int thrdaddr;
235
236 pDetails->func = fn;
237 pDetails->arg = arg;
238
239#if defined(HAVE__BEGINTHREADEX)
240 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
241 &thrdaddr);
242 if (hThread == 0)
243#elif defined(HAVE_CREATETHREAD)
244 hThread = CreateThread(NULL, 0,
245 (LPTHREAD_START_ROUTINE) threadIntermediary,
246 (void*) pDetails, 0, (DWORD*) &thrdaddr);
247 if (hThread == NULL)
248#endif
249 {
Steve Block8b4cf772011-10-12 17:27:03 +0100250 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800251 return false;
252 }
253
254#if defined(HAVE_CREATETHREAD)
255 /* close the management handle */
256 CloseHandle(hThread);
257#endif
258
259 if (id != NULL) {
260 *id = (android_thread_id_t)thrdaddr;
261 }
262
263 return true;
264}
265
266int androidCreateRawThreadEtc(android_thread_func_t fn,
267 void *userData,
268 const char* threadName,
269 int32_t threadPriority,
270 size_t threadStackSize,
271 android_thread_id_t *threadId)
272{
273 return doCreateThread( fn, userData, threadId);
274}
275
276android_thread_id_t androidGetThreadId()
277{
278 return (android_thread_id_t)GetCurrentThreadId();
279}
280
281// ----------------------------------------------------------------------------
282#else
283#error "Threads not supported"
284#endif
285
286// ----------------------------------------------------------------------------
287
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800288int androidCreateThread(android_thread_func_t fn, void* arg)
289{
290 return createThreadEtc(fn, arg);
291}
292
293int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
294{
295 return createThreadEtc(fn, arg, "android:unnamed_thread",
296 PRIORITY_DEFAULT, 0, id);
297}
298
299static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
300
301int androidCreateThreadEtc(android_thread_func_t entryFunction,
302 void *userData,
303 const char* threadName,
304 int32_t threadPriority,
305 size_t threadStackSize,
306 android_thread_id_t *threadId)
307{
308 return gCreateThreadFn(entryFunction, userData, threadName,
309 threadPriority, threadStackSize, threadId);
310}
311
312void androidSetCreateThreadFunc(android_create_thread_fn func)
313{
314 gCreateThreadFn = func;
315}
316
Dianne Hackborn235af972009-12-07 17:59:37 -0800317pid_t androidGetTid()
318{
319#ifdef HAVE_GETTID
320 return gettid();
321#else
322 return getpid();
323#endif
324}
325
326int androidSetThreadSchedulingGroup(pid_t tid, int grp)
327{
328 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
329 return BAD_VALUE;
330 }
331
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800332#if defined(HAVE_PTHREADS)
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700333 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
334 if (gDoSchedulingGroup) {
Glenn Kasten5e0243f2011-06-22 17:42:23 -0700335 // set_sched_policy does not support tid == 0
336 if (tid == 0) {
337 tid = androidGetTid();
338 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700339 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
340 SP_BACKGROUND : SP_FOREGROUND)) {
341 return PERMISSION_DENIED;
342 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800343 }
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800344#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800345
346 return NO_ERROR;
347}
348
349int androidSetThreadPriority(pid_t tid, int pri)
350{
351 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800352
353#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800354 int lasterr = 0;
355
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700356 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
357 if (gDoSchedulingGroup) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700358 // set_sched_policy does not support tid == 0
359 int policy_tid;
360 if (tid == 0) {
361 policy_tid = androidGetTid();
362 } else {
363 policy_tid = tid;
364 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700365 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700366 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700367 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700368 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700369 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800370 }
371
372 if (rc) {
373 lasterr = errno;
374 }
375
376 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
377 rc = INVALID_OPERATION;
378 } else {
379 errno = lasterr;
380 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800381#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800382
383 return rc;
384}
385
Andreas Huber8ddbed92011-09-15 12:21:40 -0700386int androidGetThreadPriority(pid_t tid) {
Andreas Huber7b4ce612011-09-16 11:47:13 -0700387#if defined(HAVE_PTHREADS)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700388 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700389#else
390 return ANDROID_PRIORITY_NORMAL;
391#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700392}
393
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700394int androidGetThreadSchedulingGroup(pid_t tid)
395{
396 int ret = ANDROID_TGROUP_DEFAULT;
397
398#if defined(HAVE_PTHREADS)
399 // convention is to not call get/set_sched_policy methods if disabled by property
400 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
401 if (gDoSchedulingGroup) {
402 SchedPolicy policy;
403 // get_sched_policy does not support tid == 0
404 if (tid == 0) {
405 tid = androidGetTid();
406 }
407 if (get_sched_policy(tid, &policy) < 0) {
408 ret = INVALID_OPERATION;
409 } else {
410 switch (policy) {
411 case SP_BACKGROUND:
412 ret = ANDROID_TGROUP_BG_NONINTERACT;
413 break;
414 case SP_FOREGROUND:
415 ret = ANDROID_TGROUP_FG_BOOST;
416 break;
417 default:
418 // should not happen, as enum SchedPolicy does not have any other values
419 ret = INVALID_OPERATION;
420 break;
421 }
422 }
423 }
424#endif
425
426 return ret;
427}
428
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800429namespace android {
430
431/*
432 * ===========================================================================
433 * Mutex class
434 * ===========================================================================
435 */
436
Mathias Agopian15554362009-07-12 23:11:20 -0700437#if defined(HAVE_PTHREADS)
438// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800439#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800440
441Mutex::Mutex()
442{
443 HANDLE hMutex;
444
445 assert(sizeof(hMutex) == sizeof(mState));
446
447 hMutex = CreateMutex(NULL, FALSE, NULL);
448 mState = (void*) hMutex;
449}
450
451Mutex::Mutex(const char* name)
452{
453 // XXX: name not used for now
454 HANDLE hMutex;
455
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200456 assert(sizeof(hMutex) == sizeof(mState));
457
458 hMutex = CreateMutex(NULL, FALSE, NULL);
459 mState = (void*) hMutex;
460}
461
462Mutex::Mutex(int type, const char* name)
463{
464 // XXX: type and name not used for now
465 HANDLE hMutex;
466
467 assert(sizeof(hMutex) == sizeof(mState));
468
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800469 hMutex = CreateMutex(NULL, FALSE, NULL);
470 mState = (void*) hMutex;
471}
472
473Mutex::~Mutex()
474{
475 CloseHandle((HANDLE) mState);
476}
477
478status_t Mutex::lock()
479{
480 DWORD dwWaitResult;
481 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
482 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
483}
484
485void Mutex::unlock()
486{
487 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100488 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800489}
490
491status_t Mutex::tryLock()
492{
493 DWORD dwWaitResult;
494
495 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
496 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100497 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800498 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
499}
500
501#else
502#error "Somebody forgot to implement threads for this platform."
503#endif
504
505
506/*
507 * ===========================================================================
508 * Condition class
509 * ===========================================================================
510 */
511
Mathias Agopian15554362009-07-12 23:11:20 -0700512#if defined(HAVE_PTHREADS)
513// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800514#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800515
516/*
517 * Windows doesn't have a condition variable solution. It's possible
518 * to create one, but it's easy to get it wrong. For a discussion, and
519 * the origin of this implementation, see:
520 *
521 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
522 *
523 * The implementation shown on the page does NOT follow POSIX semantics.
524 * As an optimization they require acquiring the external mutex before
525 * calling signal() and broadcast(), whereas POSIX only requires grabbing
526 * it before calling wait(). The implementation here has been un-optimized
527 * to have the correct behavior.
528 */
529typedef struct WinCondition {
530 // Number of waiting threads.
531 int waitersCount;
532
533 // Serialize access to waitersCount.
534 CRITICAL_SECTION waitersCountLock;
535
536 // Semaphore used to queue up threads waiting for the condition to
537 // become signaled.
538 HANDLE sema;
539
540 // An auto-reset event used by the broadcast/signal thread to wait
541 // for all the waiting thread(s) to wake up and be released from
542 // the semaphore.
543 HANDLE waitersDone;
544
545 // This mutex wouldn't be necessary if we required that the caller
546 // lock the external mutex before calling signal() and broadcast().
547 // I'm trying to mimic pthread semantics though.
548 HANDLE internalMutex;
549
550 // Keeps track of whether we were broadcasting or signaling. This
551 // allows us to optimize the code if we're just signaling.
552 bool wasBroadcast;
553
554 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
555 {
556 // Increment the wait count, avoiding race conditions.
557 EnterCriticalSection(&condState->waitersCountLock);
558 condState->waitersCount++;
559 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
560 // condState->waitersCount, getThreadId());
561 LeaveCriticalSection(&condState->waitersCountLock);
562
563 DWORD timeout = INFINITE;
564 if (abstime) {
565 nsecs_t reltime = *abstime - systemTime();
566 if (reltime < 0)
567 reltime = 0;
568 timeout = reltime/1000000;
569 }
570
571 // Atomically release the external mutex and wait on the semaphore.
572 DWORD res =
573 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
574
575 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
576
577 // Reacquire lock to avoid race conditions.
578 EnterCriticalSection(&condState->waitersCountLock);
579
580 // No longer waiting.
581 condState->waitersCount--;
582
583 // Check to see if we're the last waiter after a broadcast.
584 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
585
586 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
587 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
588
589 LeaveCriticalSection(&condState->waitersCountLock);
590
591 // If we're the last waiter thread during this particular broadcast
592 // then signal broadcast() that we're all awake. It'll drop the
593 // internal mutex.
594 if (lastWaiter) {
595 // Atomically signal the "waitersDone" event and wait until we
596 // can acquire the internal mutex. We want to do this in one step
597 // because it ensures that everybody is in the mutex FIFO before
598 // any thread has a chance to run. Without it, another thread
599 // could wake up, do work, and hop back in ahead of us.
600 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
601 INFINITE, FALSE);
602 } else {
603 // Grab the internal mutex.
604 WaitForSingleObject(condState->internalMutex, INFINITE);
605 }
606
607 // Release the internal and grab the external.
608 ReleaseMutex(condState->internalMutex);
609 WaitForSingleObject(hMutex, INFINITE);
610
611 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
612 }
613} WinCondition;
614
615/*
616 * Constructor. Set up the WinCondition stuff.
617 */
618Condition::Condition()
619{
620 WinCondition* condState = new WinCondition;
621
622 condState->waitersCount = 0;
623 condState->wasBroadcast = false;
624 // semaphore: no security, initial value of 0
625 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
626 InitializeCriticalSection(&condState->waitersCountLock);
627 // auto-reset event, not signaled initially
628 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
629 // used so we don't have to lock external mutex on signal/broadcast
630 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
631
632 mState = condState;
633}
634
635/*
636 * Destructor. Free Windows resources as well as our allocated storage.
637 */
638Condition::~Condition()
639{
640 WinCondition* condState = (WinCondition*) mState;
641 if (condState != NULL) {
642 CloseHandle(condState->sema);
643 CloseHandle(condState->waitersDone);
644 delete condState;
645 }
646}
647
648
649status_t Condition::wait(Mutex& mutex)
650{
651 WinCondition* condState = (WinCondition*) mState;
652 HANDLE hMutex = (HANDLE) mutex.mState;
653
654 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
655}
656
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800657status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
658{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200659 WinCondition* condState = (WinCondition*) mState;
660 HANDLE hMutex = (HANDLE) mutex.mState;
661 nsecs_t absTime = systemTime()+reltime;
662
663 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800664}
665
666/*
667 * Signal the condition variable, allowing one thread to continue.
668 */
669void Condition::signal()
670{
671 WinCondition* condState = (WinCondition*) mState;
672
673 // Lock the internal mutex. This ensures that we don't clash with
674 // broadcast().
675 WaitForSingleObject(condState->internalMutex, INFINITE);
676
677 EnterCriticalSection(&condState->waitersCountLock);
678 bool haveWaiters = (condState->waitersCount > 0);
679 LeaveCriticalSection(&condState->waitersCountLock);
680
681 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
682 // down a notch.
683 if (haveWaiters)
684 ReleaseSemaphore(condState->sema, 1, 0);
685
686 // Release internal mutex.
687 ReleaseMutex(condState->internalMutex);
688}
689
690/*
691 * Signal the condition variable, allowing all threads to continue.
692 *
693 * First we have to wake up all threads waiting on the semaphore, then
694 * we wait until all of the threads have actually been woken before
695 * releasing the internal mutex. This ensures that all threads are woken.
696 */
697void Condition::broadcast()
698{
699 WinCondition* condState = (WinCondition*) mState;
700
701 // Lock the internal mutex. This keeps the guys we're waking up
702 // from getting too far.
703 WaitForSingleObject(condState->internalMutex, INFINITE);
704
705 EnterCriticalSection(&condState->waitersCountLock);
706 bool haveWaiters = false;
707
708 if (condState->waitersCount > 0) {
709 haveWaiters = true;
710 condState->wasBroadcast = true;
711 }
712
713 if (haveWaiters) {
714 // Wake up all the waiters.
715 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
716
717 LeaveCriticalSection(&condState->waitersCountLock);
718
719 // Wait for all awakened threads to acquire the counting semaphore.
720 // The last guy who was waiting sets this.
721 WaitForSingleObject(condState->waitersDone, INFINITE);
722
723 // Reset wasBroadcast. (No crit section needed because nobody
724 // else can wake up to poke at it.)
725 condState->wasBroadcast = 0;
726 } else {
727 // nothing to do
728 LeaveCriticalSection(&condState->waitersCountLock);
729 }
730
731 // Release internal mutex.
732 ReleaseMutex(condState->internalMutex);
733}
734
735#else
736#error "condition variables not supported on this platform"
737#endif
738
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800739// ----------------------------------------------------------------------------
740
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800741/*
742 * This is our thread object!
743 */
744
745Thread::Thread(bool canCallJava)
746 : mCanCallJava(canCallJava),
747 mThread(thread_id_t(-1)),
748 mLock("Thread::mLock"),
749 mStatus(NO_ERROR),
750 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800751#ifdef HAVE_ANDROID_OS
752 , mTid(-1)
753#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800754{
755}
756
757Thread::~Thread()
758{
759}
760
761status_t Thread::readyToRun()
762{
763 return NO_ERROR;
764}
765
766status_t Thread::run(const char* name, int32_t priority, size_t stack)
767{
768 Mutex::Autolock _l(mLock);
769
770 if (mRunning) {
771 // thread already started
772 return INVALID_OPERATION;
773 }
774
775 // reset status and exitPending to their default value, so we can
776 // try again after an error happened (either below, or in readyToRun())
777 mStatus = NO_ERROR;
778 mExitPending = false;
779 mThread = thread_id_t(-1);
780
781 // hold a strong reference on ourself
782 mHoldSelf = this;
783
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800784 mRunning = true;
785
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800786 bool res;
787 if (mCanCallJava) {
788 res = createThreadEtc(_threadLoop,
789 this, name, priority, stack, &mThread);
790 } else {
791 res = androidCreateRawThreadEtc(_threadLoop,
792 this, name, priority, stack, &mThread);
793 }
794
795 if (res == false) {
796 mStatus = UNKNOWN_ERROR; // something happened!
797 mRunning = false;
798 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800799 mHoldSelf.clear(); // "this" may have gone away after this.
800
801 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800802 }
803
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800804 // Do not refer to mStatus here: The thread is already running (may, in fact
805 // already have exited with a valid mStatus result). The NO_ERROR indication
806 // here merely indicates successfully starting the thread and does not
807 // imply successful termination/execution.
808 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800809
810 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800811}
812
813int Thread::_threadLoop(void* user)
814{
815 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800816
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800817 sp<Thread> strong(self->mHoldSelf);
818 wp<Thread> weak(strong);
819 self->mHoldSelf.clear();
820
Kenny Rootdafff0b2011-02-16 10:13:53 -0800821#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700822 // this is very useful for debugging with gdb
823 self->mTid = gettid();
824#endif
825
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800826 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800827
828 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800829 bool result;
830 if (first) {
831 first = false;
832 self->mStatus = self->readyToRun();
833 result = (self->mStatus == NO_ERROR);
834
Glenn Kasten966a48f2011-02-01 11:32:29 -0800835 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800836 // Binder threads (and maybe others) rely on threadLoop
837 // running at least once after a successful ::readyToRun()
838 // (unless, of course, the thread has already been asked to exit
839 // at that point).
840 // This is because threads are essentially used like this:
841 // (new ThreadSubclass())->run();
842 // The caller therefore does not retain a strong reference to
843 // the thread and the thread would simply disappear after the
844 // successful ::readyToRun() call instead of entering the
845 // threadLoop at least once.
846 result = self->threadLoop();
847 }
848 } else {
849 result = self->threadLoop();
850 }
851
Glenn Kasten966a48f2011-02-01 11:32:29 -0800852 // establish a scope for mLock
853 {
854 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800855 if (result == false || self->mExitPending) {
856 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800857 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800858 // clear thread ID so that requestExitAndWait() does not exit if
859 // called by a new thread using the same thread ID as this one.
860 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800861 // note that interested observers blocked in requestExitAndWait are
862 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700863 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800864 break;
865 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800866 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800867
868 // Release our strong reference, to let a chance to the thread
869 // to die a peaceful death.
870 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700871 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800872 strong = weak.promote();
873 } while(strong != 0);
874
875 return 0;
876}
877
878void Thread::requestExit()
879{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800880 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800881 mExitPending = true;
882}
883
884status_t Thread::requestExitAndWait()
885{
Glenn Kastena538e262011-06-02 08:59:28 -0700886 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800887 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000888 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800889 "Thread (this=%p): don't call waitForExit() from this "
890 "Thread object's thread. It's a guaranteed deadlock!",
891 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800892
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800893 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800894 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800895
Glenn Kastena538e262011-06-02 08:59:28 -0700896 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800897
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800898 while (mRunning == true) {
899 mThreadExitedCondition.wait(mLock);
900 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800901 // This next line is probably not needed any more, but is being left for
902 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800903 mExitPending = false;
904
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800905 return mStatus;
906}
907
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700908status_t Thread::join()
909{
910 Mutex::Autolock _l(mLock);
911 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000912 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700913 "Thread (this=%p): don't call join() from this "
914 "Thread object's thread. It's a guaranteed deadlock!",
915 this);
916
917 return WOULD_BLOCK;
918 }
919
920 while (mRunning == true) {
921 mThreadExitedCondition.wait(mLock);
922 }
923
924 return mStatus;
925}
926
Glenn Kastend731f072011-07-11 15:59:22 -0700927#ifdef HAVE_ANDROID_OS
928pid_t Thread::getTid() const
929{
930 // mTid is not defined until the child initializes it, and the caller may need it earlier
931 Mutex::Autolock _l(mLock);
932 pid_t tid;
933 if (mRunning) {
934 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
935 tid = __pthread_gettid(pthread);
936 } else {
937 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
938 tid = -1;
939 }
940 return tid;
941}
942#endif
943
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800944bool Thread::exitPending() const
945{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800946 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800947 return mExitPending;
948}
949
950
951
952}; // namespace android