blob: f9277de73b3cb9fa65205769815b5de654be47b4 [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
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700326#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800327int androidSetThreadSchedulingGroup(pid_t tid, int grp)
328{
329 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
330 return BAD_VALUE;
331 }
332
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800333#if defined(HAVE_PTHREADS)
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700334 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
335 if (gDoSchedulingGroup) {
Glenn Kasten5e0243f2011-06-22 17:42:23 -0700336 // set_sched_policy does not support tid == 0
337 if (tid == 0) {
338 tid = androidGetTid();
339 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700340 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
341 SP_BACKGROUND : SP_FOREGROUND)) {
342 return PERMISSION_DENIED;
343 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800344 }
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800345#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800346
347 return NO_ERROR;
348}
349
350int androidSetThreadPriority(pid_t tid, int pri)
351{
352 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800353
354#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800355 int lasterr = 0;
356
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700357 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
358 if (gDoSchedulingGroup) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700359 // set_sched_policy does not support tid == 0
360 int policy_tid;
361 if (tid == 0) {
362 policy_tid = androidGetTid();
363 } else {
364 policy_tid = tid;
365 }
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700366 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700367 rc = set_sched_policy(policy_tid, SP_BACKGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700368 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
Glenn Kasten47f48572011-06-14 10:35:34 -0700369 rc = set_sched_policy(policy_tid, SP_FOREGROUND);
Dianne Hackborn16d217e2010-09-03 17:07:07 -0700370 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800371 }
372
373 if (rc) {
374 lasterr = errno;
375 }
376
377 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
378 rc = INVALID_OPERATION;
379 } else {
380 errno = lasterr;
381 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800382#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800383
384 return rc;
385}
386
Andreas Huber8ddbed92011-09-15 12:21:40 -0700387int androidGetThreadPriority(pid_t tid) {
Andreas Huber7b4ce612011-09-16 11:47:13 -0700388#if defined(HAVE_PTHREADS)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700389 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700390#else
391 return ANDROID_PRIORITY_NORMAL;
392#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700393}
394
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700395int androidGetThreadSchedulingGroup(pid_t tid)
396{
397 int ret = ANDROID_TGROUP_DEFAULT;
398
399#if defined(HAVE_PTHREADS)
400 // convention is to not call get/set_sched_policy methods if disabled by property
401 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
402 if (gDoSchedulingGroup) {
403 SchedPolicy policy;
404 // get_sched_policy does not support tid == 0
405 if (tid == 0) {
406 tid = androidGetTid();
407 }
408 if (get_sched_policy(tid, &policy) < 0) {
409 ret = INVALID_OPERATION;
410 } else {
411 switch (policy) {
412 case SP_BACKGROUND:
413 ret = ANDROID_TGROUP_BG_NONINTERACT;
414 break;
415 case SP_FOREGROUND:
416 ret = ANDROID_TGROUP_FG_BOOST;
417 break;
418 default:
419 // should not happen, as enum SchedPolicy does not have any other values
420 ret = INVALID_OPERATION;
421 break;
422 }
423 }
424 }
425#endif
426
427 return ret;
428}
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700429#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700430
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800431namespace android {
432
433/*
434 * ===========================================================================
435 * Mutex class
436 * ===========================================================================
437 */
438
Mathias Agopian15554362009-07-12 23:11:20 -0700439#if defined(HAVE_PTHREADS)
440// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800441#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800442
443Mutex::Mutex()
444{
445 HANDLE hMutex;
446
447 assert(sizeof(hMutex) == sizeof(mState));
448
449 hMutex = CreateMutex(NULL, FALSE, NULL);
450 mState = (void*) hMutex;
451}
452
453Mutex::Mutex(const char* name)
454{
455 // XXX: name not used for now
456 HANDLE hMutex;
457
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200458 assert(sizeof(hMutex) == sizeof(mState));
459
460 hMutex = CreateMutex(NULL, FALSE, NULL);
461 mState = (void*) hMutex;
462}
463
464Mutex::Mutex(int type, const char* name)
465{
466 // XXX: type and name not used for now
467 HANDLE hMutex;
468
469 assert(sizeof(hMutex) == sizeof(mState));
470
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800471 hMutex = CreateMutex(NULL, FALSE, NULL);
472 mState = (void*) hMutex;
473}
474
475Mutex::~Mutex()
476{
477 CloseHandle((HANDLE) mState);
478}
479
480status_t Mutex::lock()
481{
482 DWORD dwWaitResult;
483 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
484 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
485}
486
487void Mutex::unlock()
488{
489 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100490 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800491}
492
493status_t Mutex::tryLock()
494{
495 DWORD dwWaitResult;
496
497 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
498 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100499 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800500 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
501}
502
503#else
504#error "Somebody forgot to implement threads for this platform."
505#endif
506
507
508/*
509 * ===========================================================================
510 * Condition class
511 * ===========================================================================
512 */
513
Mathias Agopian15554362009-07-12 23:11:20 -0700514#if defined(HAVE_PTHREADS)
515// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800516#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800517
518/*
519 * Windows doesn't have a condition variable solution. It's possible
520 * to create one, but it's easy to get it wrong. For a discussion, and
521 * the origin of this implementation, see:
522 *
523 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
524 *
525 * The implementation shown on the page does NOT follow POSIX semantics.
526 * As an optimization they require acquiring the external mutex before
527 * calling signal() and broadcast(), whereas POSIX only requires grabbing
528 * it before calling wait(). The implementation here has been un-optimized
529 * to have the correct behavior.
530 */
531typedef struct WinCondition {
532 // Number of waiting threads.
533 int waitersCount;
534
535 // Serialize access to waitersCount.
536 CRITICAL_SECTION waitersCountLock;
537
538 // Semaphore used to queue up threads waiting for the condition to
539 // become signaled.
540 HANDLE sema;
541
542 // An auto-reset event used by the broadcast/signal thread to wait
543 // for all the waiting thread(s) to wake up and be released from
544 // the semaphore.
545 HANDLE waitersDone;
546
547 // This mutex wouldn't be necessary if we required that the caller
548 // lock the external mutex before calling signal() and broadcast().
549 // I'm trying to mimic pthread semantics though.
550 HANDLE internalMutex;
551
552 // Keeps track of whether we were broadcasting or signaling. This
553 // allows us to optimize the code if we're just signaling.
554 bool wasBroadcast;
555
556 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
557 {
558 // Increment the wait count, avoiding race conditions.
559 EnterCriticalSection(&condState->waitersCountLock);
560 condState->waitersCount++;
561 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
562 // condState->waitersCount, getThreadId());
563 LeaveCriticalSection(&condState->waitersCountLock);
564
565 DWORD timeout = INFINITE;
566 if (abstime) {
567 nsecs_t reltime = *abstime - systemTime();
568 if (reltime < 0)
569 reltime = 0;
570 timeout = reltime/1000000;
571 }
572
573 // Atomically release the external mutex and wait on the semaphore.
574 DWORD res =
575 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
576
577 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
578
579 // Reacquire lock to avoid race conditions.
580 EnterCriticalSection(&condState->waitersCountLock);
581
582 // No longer waiting.
583 condState->waitersCount--;
584
585 // Check to see if we're the last waiter after a broadcast.
586 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
587
588 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
589 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
590
591 LeaveCriticalSection(&condState->waitersCountLock);
592
593 // If we're the last waiter thread during this particular broadcast
594 // then signal broadcast() that we're all awake. It'll drop the
595 // internal mutex.
596 if (lastWaiter) {
597 // Atomically signal the "waitersDone" event and wait until we
598 // can acquire the internal mutex. We want to do this in one step
599 // because it ensures that everybody is in the mutex FIFO before
600 // any thread has a chance to run. Without it, another thread
601 // could wake up, do work, and hop back in ahead of us.
602 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
603 INFINITE, FALSE);
604 } else {
605 // Grab the internal mutex.
606 WaitForSingleObject(condState->internalMutex, INFINITE);
607 }
608
609 // Release the internal and grab the external.
610 ReleaseMutex(condState->internalMutex);
611 WaitForSingleObject(hMutex, INFINITE);
612
613 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
614 }
615} WinCondition;
616
617/*
618 * Constructor. Set up the WinCondition stuff.
619 */
620Condition::Condition()
621{
622 WinCondition* condState = new WinCondition;
623
624 condState->waitersCount = 0;
625 condState->wasBroadcast = false;
626 // semaphore: no security, initial value of 0
627 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
628 InitializeCriticalSection(&condState->waitersCountLock);
629 // auto-reset event, not signaled initially
630 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
631 // used so we don't have to lock external mutex on signal/broadcast
632 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
633
634 mState = condState;
635}
636
637/*
638 * Destructor. Free Windows resources as well as our allocated storage.
639 */
640Condition::~Condition()
641{
642 WinCondition* condState = (WinCondition*) mState;
643 if (condState != NULL) {
644 CloseHandle(condState->sema);
645 CloseHandle(condState->waitersDone);
646 delete condState;
647 }
648}
649
650
651status_t Condition::wait(Mutex& mutex)
652{
653 WinCondition* condState = (WinCondition*) mState;
654 HANDLE hMutex = (HANDLE) mutex.mState;
655
656 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
657}
658
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800659status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
660{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200661 WinCondition* condState = (WinCondition*) mState;
662 HANDLE hMutex = (HANDLE) mutex.mState;
663 nsecs_t absTime = systemTime()+reltime;
664
665 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800666}
667
668/*
669 * Signal the condition variable, allowing one thread to continue.
670 */
671void Condition::signal()
672{
673 WinCondition* condState = (WinCondition*) mState;
674
675 // Lock the internal mutex. This ensures that we don't clash with
676 // broadcast().
677 WaitForSingleObject(condState->internalMutex, INFINITE);
678
679 EnterCriticalSection(&condState->waitersCountLock);
680 bool haveWaiters = (condState->waitersCount > 0);
681 LeaveCriticalSection(&condState->waitersCountLock);
682
683 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
684 // down a notch.
685 if (haveWaiters)
686 ReleaseSemaphore(condState->sema, 1, 0);
687
688 // Release internal mutex.
689 ReleaseMutex(condState->internalMutex);
690}
691
692/*
693 * Signal the condition variable, allowing all threads to continue.
694 *
695 * First we have to wake up all threads waiting on the semaphore, then
696 * we wait until all of the threads have actually been woken before
697 * releasing the internal mutex. This ensures that all threads are woken.
698 */
699void Condition::broadcast()
700{
701 WinCondition* condState = (WinCondition*) mState;
702
703 // Lock the internal mutex. This keeps the guys we're waking up
704 // from getting too far.
705 WaitForSingleObject(condState->internalMutex, INFINITE);
706
707 EnterCriticalSection(&condState->waitersCountLock);
708 bool haveWaiters = false;
709
710 if (condState->waitersCount > 0) {
711 haveWaiters = true;
712 condState->wasBroadcast = true;
713 }
714
715 if (haveWaiters) {
716 // Wake up all the waiters.
717 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
718
719 LeaveCriticalSection(&condState->waitersCountLock);
720
721 // Wait for all awakened threads to acquire the counting semaphore.
722 // The last guy who was waiting sets this.
723 WaitForSingleObject(condState->waitersDone, INFINITE);
724
725 // Reset wasBroadcast. (No crit section needed because nobody
726 // else can wake up to poke at it.)
727 condState->wasBroadcast = 0;
728 } else {
729 // nothing to do
730 LeaveCriticalSection(&condState->waitersCountLock);
731 }
732
733 // Release internal mutex.
734 ReleaseMutex(condState->internalMutex);
735}
736
737#else
738#error "condition variables not supported on this platform"
739#endif
740
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800741// ----------------------------------------------------------------------------
742
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800743/*
744 * This is our thread object!
745 */
746
747Thread::Thread(bool canCallJava)
748 : mCanCallJava(canCallJava),
749 mThread(thread_id_t(-1)),
750 mLock("Thread::mLock"),
751 mStatus(NO_ERROR),
752 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800753#ifdef HAVE_ANDROID_OS
754 , mTid(-1)
755#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800756{
757}
758
759Thread::~Thread()
760{
761}
762
763status_t Thread::readyToRun()
764{
765 return NO_ERROR;
766}
767
768status_t Thread::run(const char* name, int32_t priority, size_t stack)
769{
770 Mutex::Autolock _l(mLock);
771
772 if (mRunning) {
773 // thread already started
774 return INVALID_OPERATION;
775 }
776
777 // reset status and exitPending to their default value, so we can
778 // try again after an error happened (either below, or in readyToRun())
779 mStatus = NO_ERROR;
780 mExitPending = false;
781 mThread = thread_id_t(-1);
782
783 // hold a strong reference on ourself
784 mHoldSelf = this;
785
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800786 mRunning = true;
787
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800788 bool res;
789 if (mCanCallJava) {
790 res = createThreadEtc(_threadLoop,
791 this, name, priority, stack, &mThread);
792 } else {
793 res = androidCreateRawThreadEtc(_threadLoop,
794 this, name, priority, stack, &mThread);
795 }
796
797 if (res == false) {
798 mStatus = UNKNOWN_ERROR; // something happened!
799 mRunning = false;
800 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800801 mHoldSelf.clear(); // "this" may have gone away after this.
802
803 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800804 }
805
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800806 // Do not refer to mStatus here: The thread is already running (may, in fact
807 // already have exited with a valid mStatus result). The NO_ERROR indication
808 // here merely indicates successfully starting the thread and does not
809 // imply successful termination/execution.
810 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800811
812 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800813}
814
815int Thread::_threadLoop(void* user)
816{
817 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800818
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800819 sp<Thread> strong(self->mHoldSelf);
820 wp<Thread> weak(strong);
821 self->mHoldSelf.clear();
822
Kenny Rootdafff0b2011-02-16 10:13:53 -0800823#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700824 // this is very useful for debugging with gdb
825 self->mTid = gettid();
826#endif
827
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800828 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800829
830 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800831 bool result;
832 if (first) {
833 first = false;
834 self->mStatus = self->readyToRun();
835 result = (self->mStatus == NO_ERROR);
836
Glenn Kasten966a48f2011-02-01 11:32:29 -0800837 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800838 // Binder threads (and maybe others) rely on threadLoop
839 // running at least once after a successful ::readyToRun()
840 // (unless, of course, the thread has already been asked to exit
841 // at that point).
842 // This is because threads are essentially used like this:
843 // (new ThreadSubclass())->run();
844 // The caller therefore does not retain a strong reference to
845 // the thread and the thread would simply disappear after the
846 // successful ::readyToRun() call instead of entering the
847 // threadLoop at least once.
848 result = self->threadLoop();
849 }
850 } else {
851 result = self->threadLoop();
852 }
853
Glenn Kasten966a48f2011-02-01 11:32:29 -0800854 // establish a scope for mLock
855 {
856 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800857 if (result == false || self->mExitPending) {
858 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800859 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800860 // clear thread ID so that requestExitAndWait() does not exit if
861 // called by a new thread using the same thread ID as this one.
862 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800863 // note that interested observers blocked in requestExitAndWait are
864 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700865 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800866 break;
867 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800868 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800869
870 // Release our strong reference, to let a chance to the thread
871 // to die a peaceful death.
872 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700873 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800874 strong = weak.promote();
875 } while(strong != 0);
876
877 return 0;
878}
879
880void Thread::requestExit()
881{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800882 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800883 mExitPending = true;
884}
885
886status_t Thread::requestExitAndWait()
887{
Glenn Kastena538e262011-06-02 08:59:28 -0700888 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800889 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000890 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800891 "Thread (this=%p): don't call waitForExit() from this "
892 "Thread object's thread. It's a guaranteed deadlock!",
893 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800894
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800895 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800896 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800897
Glenn Kastena538e262011-06-02 08:59:28 -0700898 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800899
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800900 while (mRunning == true) {
901 mThreadExitedCondition.wait(mLock);
902 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800903 // This next line is probably not needed any more, but is being left for
904 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800905 mExitPending = false;
906
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800907 return mStatus;
908}
909
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700910status_t Thread::join()
911{
912 Mutex::Autolock _l(mLock);
913 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000914 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700915 "Thread (this=%p): don't call join() from this "
916 "Thread object's thread. It's a guaranteed deadlock!",
917 this);
918
919 return WOULD_BLOCK;
920 }
921
922 while (mRunning == true) {
923 mThreadExitedCondition.wait(mLock);
924 }
925
926 return mStatus;
927}
928
Glenn Kastend731f072011-07-11 15:59:22 -0700929#ifdef HAVE_ANDROID_OS
930pid_t Thread::getTid() const
931{
932 // mTid is not defined until the child initializes it, and the caller may need it earlier
933 Mutex::Autolock _l(mLock);
934 pid_t tid;
935 if (mRunning) {
936 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
937 tid = __pthread_gettid(pthread);
938 } else {
939 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
940 tid = -1;
941 }
942 return tid;
943}
944#endif
945
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800946bool Thread::exitPending() const
947{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800948 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800949 return mExitPending;
950}
951
952
953
954}; // namespace android