blob: cc7fe899323513bbbbd3b6887b0c0ea15ad3ef14 [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
Mark Salyzyn5bed8032014-04-30 11:10:46 -070020#include <assert.h>
21#include <errno.h>
22#include <memory.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080023#include <stdio.h>
24#include <stdlib.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025#include <unistd.h>
26
27#if defined(HAVE_PTHREADS)
28# include <pthread.h>
29# include <sched.h>
30# include <sys/resource.h>
Glenn Kastend731f072011-07-11 15:59:22 -070031#ifdef HAVE_ANDROID_OS
32# include <bionic_pthread.h>
33#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080034#elif defined(HAVE_WIN32_THREADS)
35# include <windows.h>
36# include <stdint.h>
37# include <process.h>
38# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
39#endif
40
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080041#if defined(HAVE_PRCTL)
42#include <sys/prctl.h>
43#endif
44
Mark Salyzyn5bed8032014-04-30 11:10:46 -070045#include <utils/threads.h>
46#include <utils/Log.h>
47
48#include <cutils/sched_policy.h>
49
50#ifdef HAVE_ANDROID_OS
51# define __android_unused
52#else
53# define __android_unused __attribute__((__unused__))
54#endif
55
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080056/*
57 * ===========================================================================
58 * Thread wrappers
59 * ===========================================================================
60 */
61
62using namespace android;
63
64// ----------------------------------------------------------------------------
65#if defined(HAVE_PTHREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080066// ----------------------------------------------------------------------------
67
68/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070069 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080070 *
71 * We create it "detached", so it cleans up after itself.
72 */
73
74typedef void* (*android_pthread_entry)(void*);
75
76struct thread_data_t {
77 thread_func_t entryFunction;
78 void* userData;
79 int priority;
80 char * threadName;
81
82 // we use this trampoline when we need to set the priority with
Glenn Kastend731f072011-07-11 15:59:22 -070083 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080084 static int trampoline(const thread_data_t* t) {
85 thread_func_t f = t->entryFunction;
86 void* u = t->userData;
87 int prio = t->priority;
88 char * name = t->threadName;
89 delete t;
90 setpriority(PRIO_PROCESS, 0, prio);
Glenn Kastenfe34e452012-04-30 16:03:30 -070091 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
92 set_sched_policy(0, SP_BACKGROUND);
93 } else {
94 set_sched_policy(0, SP_FOREGROUND);
Dianne Hackborna78bab02010-09-09 15:50:18 -070095 }
96
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080097 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080098 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080099 free(name);
100 }
101 return f(u);
102 }
103};
104
Mathias Agopian6090df82013-03-07 15:34:28 -0800105void androidSetThreadName(const char* name) {
106#if defined(HAVE_PRCTL)
107 // Mac OS doesn't have this, and we build libutil for the host too
108 int hasAt = 0;
109 int hasDot = 0;
110 const char *s = name;
111 while (*s) {
112 if (*s == '.') hasDot = 1;
113 else if (*s == '@') hasAt = 1;
114 s++;
115 }
116 int len = s - name;
117 if (len < 15 || hasAt || !hasDot) {
118 s = name;
119 } else {
120 s = name + len - 15;
121 }
122 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
123#endif
124}
125
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800126int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
127 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700128 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800129 int32_t threadPriority,
130 size_t threadStackSize,
131 android_thread_id_t *threadId)
132{
133 pthread_attr_t attr;
134 pthread_attr_init(&attr);
135 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
136
137#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
138 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700139 // Now that the pthread_t has a method to find the associated
140 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
141 // this trampoline in some cases as the parent could set the properties
142 // for the child. However, there would be a race condition because the
143 // child becomes ready immediately, and it doesn't work for the name.
144 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
145 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800146 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) {
Steve Block1b781ab2012-01-06 19:20:56 +0000166 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800167 "(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
Glenn Kastend731f072011-07-11 15:59:22 -0700181#ifdef HAVE_ANDROID_OS
182static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
183{
184 return (pthread_t) thread;
185}
186#endif
187
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800188android_thread_id_t androidGetThreadId()
189{
190 return (android_thread_id_t)pthread_self();
191}
192
193// ----------------------------------------------------------------------------
194#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800195// ----------------------------------------------------------------------------
196
197/*
198 * Trampoline to make us __stdcall-compliant.
199 *
200 * We're expected to delete "vDetails" when we're done.
201 */
202struct threadDetails {
203 int (*func)(void*);
204 void* arg;
205};
206static __stdcall unsigned int threadIntermediary(void* vDetails)
207{
208 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
209 int result;
210
211 result = (*(pDetails->func))(pDetails->arg);
212
213 delete pDetails;
214
Steve Block8b4cf772011-10-12 17:27:03 +0100215 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800216 return (unsigned int) result;
217}
218
219/*
220 * Create and run a new thread.
221 */
222static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
223{
224 HANDLE hThread;
225 struct threadDetails* pDetails = new threadDetails; // must be on heap
226 unsigned int thrdaddr;
227
228 pDetails->func = fn;
229 pDetails->arg = arg;
230
231#if defined(HAVE__BEGINTHREADEX)
232 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
233 &thrdaddr);
234 if (hThread == 0)
235#elif defined(HAVE_CREATETHREAD)
236 hThread = CreateThread(NULL, 0,
237 (LPTHREAD_START_ROUTINE) threadIntermediary,
238 (void*) pDetails, 0, (DWORD*) &thrdaddr);
239 if (hThread == NULL)
240#endif
241 {
Steve Block8b4cf772011-10-12 17:27:03 +0100242 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800243 return false;
244 }
245
246#if defined(HAVE_CREATETHREAD)
247 /* close the management handle */
248 CloseHandle(hThread);
249#endif
250
251 if (id != NULL) {
252 *id = (android_thread_id_t)thrdaddr;
253 }
254
255 return true;
256}
257
258int androidCreateRawThreadEtc(android_thread_func_t fn,
259 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700260 const char* /*threadName*/,
261 int32_t /*threadPriority*/,
262 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800263 android_thread_id_t *threadId)
264{
265 return doCreateThread( fn, userData, threadId);
266}
267
268android_thread_id_t androidGetThreadId()
269{
270 return (android_thread_id_t)GetCurrentThreadId();
271}
272
273// ----------------------------------------------------------------------------
274#else
275#error "Threads not supported"
276#endif
277
278// ----------------------------------------------------------------------------
279
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800280int androidCreateThread(android_thread_func_t fn, void* arg)
281{
282 return createThreadEtc(fn, arg);
283}
284
285int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
286{
287 return createThreadEtc(fn, arg, "android:unnamed_thread",
288 PRIORITY_DEFAULT, 0, id);
289}
290
291static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
292
293int androidCreateThreadEtc(android_thread_func_t entryFunction,
294 void *userData,
295 const char* threadName,
296 int32_t threadPriority,
297 size_t threadStackSize,
298 android_thread_id_t *threadId)
299{
300 return gCreateThreadFn(entryFunction, userData, threadName,
301 threadPriority, threadStackSize, threadId);
302}
303
304void androidSetCreateThreadFunc(android_create_thread_fn func)
305{
306 gCreateThreadFn = func;
307}
308
Dianne Hackborn235af972009-12-07 17:59:37 -0800309pid_t androidGetTid()
310{
311#ifdef HAVE_GETTID
312 return gettid();
313#else
314 return getpid();
315#endif
316}
317
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700318#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800319int androidSetThreadPriority(pid_t tid, int pri)
320{
321 int rc = 0;
Dianne Hackbornaaa7ef82009-12-08 19:45:59 -0800322
323#if defined(HAVE_PTHREADS)
Dianne Hackborn235af972009-12-07 17:59:37 -0800324 int lasterr = 0;
325
Glenn Kastenfe34e452012-04-30 16:03:30 -0700326 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
327 rc = set_sched_policy(tid, SP_BACKGROUND);
328 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
329 rc = set_sched_policy(tid, SP_FOREGROUND);
Dianne Hackborn235af972009-12-07 17:59:37 -0800330 }
331
332 if (rc) {
333 lasterr = errno;
334 }
335
336 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
337 rc = INVALID_OPERATION;
338 } else {
339 errno = lasterr;
340 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800341#endif
Dianne Hackborn235af972009-12-07 17:59:37 -0800342
343 return rc;
344}
345
Andreas Huber8ddbed92011-09-15 12:21:40 -0700346int androidGetThreadPriority(pid_t tid) {
Andreas Huber7b4ce612011-09-16 11:47:13 -0700347#if defined(HAVE_PTHREADS)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700348 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700349#else
350 return ANDROID_PRIORITY_NORMAL;
351#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700352}
353
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700354#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700355
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800356namespace android {
357
358/*
359 * ===========================================================================
360 * Mutex class
361 * ===========================================================================
362 */
363
Mathias Agopian15554362009-07-12 23:11:20 -0700364#if defined(HAVE_PTHREADS)
365// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800366#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800367
368Mutex::Mutex()
369{
370 HANDLE hMutex;
371
372 assert(sizeof(hMutex) == sizeof(mState));
373
374 hMutex = CreateMutex(NULL, FALSE, NULL);
375 mState = (void*) hMutex;
376}
377
378Mutex::Mutex(const char* name)
379{
380 // XXX: name not used for now
381 HANDLE hMutex;
382
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200383 assert(sizeof(hMutex) == sizeof(mState));
384
385 hMutex = CreateMutex(NULL, FALSE, NULL);
386 mState = (void*) hMutex;
387}
388
389Mutex::Mutex(int type, const char* name)
390{
391 // XXX: type and name not used for now
392 HANDLE hMutex;
393
394 assert(sizeof(hMutex) == sizeof(mState));
395
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800396 hMutex = CreateMutex(NULL, FALSE, NULL);
397 mState = (void*) hMutex;
398}
399
400Mutex::~Mutex()
401{
402 CloseHandle((HANDLE) mState);
403}
404
405status_t Mutex::lock()
406{
407 DWORD dwWaitResult;
408 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
409 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
410}
411
412void Mutex::unlock()
413{
414 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100415 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800416}
417
418status_t Mutex::tryLock()
419{
420 DWORD dwWaitResult;
421
422 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
423 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100424 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800425 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
426}
427
428#else
429#error "Somebody forgot to implement threads for this platform."
430#endif
431
432
433/*
434 * ===========================================================================
435 * Condition 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
443/*
444 * Windows doesn't have a condition variable solution. It's possible
445 * to create one, but it's easy to get it wrong. For a discussion, and
446 * the origin of this implementation, see:
447 *
448 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
449 *
450 * The implementation shown on the page does NOT follow POSIX semantics.
451 * As an optimization they require acquiring the external mutex before
452 * calling signal() and broadcast(), whereas POSIX only requires grabbing
453 * it before calling wait(). The implementation here has been un-optimized
454 * to have the correct behavior.
455 */
456typedef struct WinCondition {
457 // Number of waiting threads.
458 int waitersCount;
459
460 // Serialize access to waitersCount.
461 CRITICAL_SECTION waitersCountLock;
462
463 // Semaphore used to queue up threads waiting for the condition to
464 // become signaled.
465 HANDLE sema;
466
467 // An auto-reset event used by the broadcast/signal thread to wait
468 // for all the waiting thread(s) to wake up and be released from
469 // the semaphore.
470 HANDLE waitersDone;
471
472 // This mutex wouldn't be necessary if we required that the caller
473 // lock the external mutex before calling signal() and broadcast().
474 // I'm trying to mimic pthread semantics though.
475 HANDLE internalMutex;
476
477 // Keeps track of whether we were broadcasting or signaling. This
478 // allows us to optimize the code if we're just signaling.
479 bool wasBroadcast;
480
481 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
482 {
483 // Increment the wait count, avoiding race conditions.
484 EnterCriticalSection(&condState->waitersCountLock);
485 condState->waitersCount++;
486 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
487 // condState->waitersCount, getThreadId());
488 LeaveCriticalSection(&condState->waitersCountLock);
489
490 DWORD timeout = INFINITE;
491 if (abstime) {
492 nsecs_t reltime = *abstime - systemTime();
493 if (reltime < 0)
494 reltime = 0;
495 timeout = reltime/1000000;
496 }
497
498 // Atomically release the external mutex and wait on the semaphore.
499 DWORD res =
500 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
501
502 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
503
504 // Reacquire lock to avoid race conditions.
505 EnterCriticalSection(&condState->waitersCountLock);
506
507 // No longer waiting.
508 condState->waitersCount--;
509
510 // Check to see if we're the last waiter after a broadcast.
511 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
512
513 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
514 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
515
516 LeaveCriticalSection(&condState->waitersCountLock);
517
518 // If we're the last waiter thread during this particular broadcast
519 // then signal broadcast() that we're all awake. It'll drop the
520 // internal mutex.
521 if (lastWaiter) {
522 // Atomically signal the "waitersDone" event and wait until we
523 // can acquire the internal mutex. We want to do this in one step
524 // because it ensures that everybody is in the mutex FIFO before
525 // any thread has a chance to run. Without it, another thread
526 // could wake up, do work, and hop back in ahead of us.
527 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
528 INFINITE, FALSE);
529 } else {
530 // Grab the internal mutex.
531 WaitForSingleObject(condState->internalMutex, INFINITE);
532 }
533
534 // Release the internal and grab the external.
535 ReleaseMutex(condState->internalMutex);
536 WaitForSingleObject(hMutex, INFINITE);
537
538 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
539 }
540} WinCondition;
541
542/*
543 * Constructor. Set up the WinCondition stuff.
544 */
545Condition::Condition()
546{
547 WinCondition* condState = new WinCondition;
548
549 condState->waitersCount = 0;
550 condState->wasBroadcast = false;
551 // semaphore: no security, initial value of 0
552 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
553 InitializeCriticalSection(&condState->waitersCountLock);
554 // auto-reset event, not signaled initially
555 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
556 // used so we don't have to lock external mutex on signal/broadcast
557 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
558
559 mState = condState;
560}
561
562/*
563 * Destructor. Free Windows resources as well as our allocated storage.
564 */
565Condition::~Condition()
566{
567 WinCondition* condState = (WinCondition*) mState;
568 if (condState != NULL) {
569 CloseHandle(condState->sema);
570 CloseHandle(condState->waitersDone);
571 delete condState;
572 }
573}
574
575
576status_t Condition::wait(Mutex& mutex)
577{
578 WinCondition* condState = (WinCondition*) mState;
579 HANDLE hMutex = (HANDLE) mutex.mState;
580
581 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
582}
583
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800584status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
585{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200586 WinCondition* condState = (WinCondition*) mState;
587 HANDLE hMutex = (HANDLE) mutex.mState;
588 nsecs_t absTime = systemTime()+reltime;
589
590 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800591}
592
593/*
594 * Signal the condition variable, allowing one thread to continue.
595 */
596void Condition::signal()
597{
598 WinCondition* condState = (WinCondition*) mState;
599
600 // Lock the internal mutex. This ensures that we don't clash with
601 // broadcast().
602 WaitForSingleObject(condState->internalMutex, INFINITE);
603
604 EnterCriticalSection(&condState->waitersCountLock);
605 bool haveWaiters = (condState->waitersCount > 0);
606 LeaveCriticalSection(&condState->waitersCountLock);
607
608 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
609 // down a notch.
610 if (haveWaiters)
611 ReleaseSemaphore(condState->sema, 1, 0);
612
613 // Release internal mutex.
614 ReleaseMutex(condState->internalMutex);
615}
616
617/*
618 * Signal the condition variable, allowing all threads to continue.
619 *
620 * First we have to wake up all threads waiting on the semaphore, then
621 * we wait until all of the threads have actually been woken before
622 * releasing the internal mutex. This ensures that all threads are woken.
623 */
624void Condition::broadcast()
625{
626 WinCondition* condState = (WinCondition*) mState;
627
628 // Lock the internal mutex. This keeps the guys we're waking up
629 // from getting too far.
630 WaitForSingleObject(condState->internalMutex, INFINITE);
631
632 EnterCriticalSection(&condState->waitersCountLock);
633 bool haveWaiters = false;
634
635 if (condState->waitersCount > 0) {
636 haveWaiters = true;
637 condState->wasBroadcast = true;
638 }
639
640 if (haveWaiters) {
641 // Wake up all the waiters.
642 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
643
644 LeaveCriticalSection(&condState->waitersCountLock);
645
646 // Wait for all awakened threads to acquire the counting semaphore.
647 // The last guy who was waiting sets this.
648 WaitForSingleObject(condState->waitersDone, INFINITE);
649
650 // Reset wasBroadcast. (No crit section needed because nobody
651 // else can wake up to poke at it.)
652 condState->wasBroadcast = 0;
653 } else {
654 // nothing to do
655 LeaveCriticalSection(&condState->waitersCountLock);
656 }
657
658 // Release internal mutex.
659 ReleaseMutex(condState->internalMutex);
660}
661
662#else
663#error "condition variables not supported on this platform"
664#endif
665
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800666// ----------------------------------------------------------------------------
667
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800668/*
669 * This is our thread object!
670 */
671
672Thread::Thread(bool canCallJava)
673 : mCanCallJava(canCallJava),
674 mThread(thread_id_t(-1)),
675 mLock("Thread::mLock"),
676 mStatus(NO_ERROR),
677 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800678#ifdef HAVE_ANDROID_OS
679 , mTid(-1)
680#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800681{
682}
683
684Thread::~Thread()
685{
686}
687
688status_t Thread::readyToRun()
689{
690 return NO_ERROR;
691}
692
693status_t Thread::run(const char* name, int32_t priority, size_t stack)
694{
695 Mutex::Autolock _l(mLock);
696
697 if (mRunning) {
698 // thread already started
699 return INVALID_OPERATION;
700 }
701
702 // reset status and exitPending to their default value, so we can
703 // try again after an error happened (either below, or in readyToRun())
704 mStatus = NO_ERROR;
705 mExitPending = false;
706 mThread = thread_id_t(-1);
707
708 // hold a strong reference on ourself
709 mHoldSelf = this;
710
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800711 mRunning = true;
712
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800713 bool res;
714 if (mCanCallJava) {
715 res = createThreadEtc(_threadLoop,
716 this, name, priority, stack, &mThread);
717 } else {
718 res = androidCreateRawThreadEtc(_threadLoop,
719 this, name, priority, stack, &mThread);
720 }
721
722 if (res == false) {
723 mStatus = UNKNOWN_ERROR; // something happened!
724 mRunning = false;
725 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800726 mHoldSelf.clear(); // "this" may have gone away after this.
727
728 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800729 }
730
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800731 // Do not refer to mStatus here: The thread is already running (may, in fact
732 // already have exited with a valid mStatus result). The NO_ERROR indication
733 // here merely indicates successfully starting the thread and does not
734 // imply successful termination/execution.
735 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800736
737 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800738}
739
740int Thread::_threadLoop(void* user)
741{
742 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800743
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800744 sp<Thread> strong(self->mHoldSelf);
745 wp<Thread> weak(strong);
746 self->mHoldSelf.clear();
747
Kenny Rootdafff0b2011-02-16 10:13:53 -0800748#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700749 // this is very useful for debugging with gdb
750 self->mTid = gettid();
751#endif
752
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800753 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800754
755 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800756 bool result;
757 if (first) {
758 first = false;
759 self->mStatus = self->readyToRun();
760 result = (self->mStatus == NO_ERROR);
761
Glenn Kasten966a48f2011-02-01 11:32:29 -0800762 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800763 // Binder threads (and maybe others) rely on threadLoop
764 // running at least once after a successful ::readyToRun()
765 // (unless, of course, the thread has already been asked to exit
766 // at that point).
767 // This is because threads are essentially used like this:
768 // (new ThreadSubclass())->run();
769 // The caller therefore does not retain a strong reference to
770 // the thread and the thread would simply disappear after the
771 // successful ::readyToRun() call instead of entering the
772 // threadLoop at least once.
773 result = self->threadLoop();
774 }
775 } else {
776 result = self->threadLoop();
777 }
778
Glenn Kasten966a48f2011-02-01 11:32:29 -0800779 // establish a scope for mLock
780 {
781 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800782 if (result == false || self->mExitPending) {
783 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800784 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800785 // clear thread ID so that requestExitAndWait() does not exit if
786 // called by a new thread using the same thread ID as this one.
787 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800788 // note that interested observers blocked in requestExitAndWait are
789 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700790 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800791 break;
792 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800793 }
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800794
795 // Release our strong reference, to let a chance to the thread
796 // to die a peaceful death.
797 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700798 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800799 strong = weak.promote();
800 } while(strong != 0);
801
802 return 0;
803}
804
805void Thread::requestExit()
806{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800807 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800808 mExitPending = true;
809}
810
811status_t Thread::requestExitAndWait()
812{
Glenn Kastena538e262011-06-02 08:59:28 -0700813 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800814 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000815 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800816 "Thread (this=%p): don't call waitForExit() from this "
817 "Thread object's thread. It's a guaranteed deadlock!",
818 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800819
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800820 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800821 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800822
Glenn Kastena538e262011-06-02 08:59:28 -0700823 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800824
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800825 while (mRunning == true) {
826 mThreadExitedCondition.wait(mLock);
827 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800828 // This next line is probably not needed any more, but is being left for
829 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800830 mExitPending = false;
831
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800832 return mStatus;
833}
834
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700835status_t Thread::join()
836{
837 Mutex::Autolock _l(mLock);
838 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000839 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700840 "Thread (this=%p): don't call join() from this "
841 "Thread object's thread. It's a guaranteed deadlock!",
842 this);
843
844 return WOULD_BLOCK;
845 }
846
847 while (mRunning == true) {
848 mThreadExitedCondition.wait(mLock);
849 }
850
851 return mStatus;
852}
853
Romain Guy31ba37f2013-03-11 14:34:56 -0700854bool Thread::isRunning() const {
855 Mutex::Autolock _l(mLock);
856 return mRunning;
857}
858
Glenn Kastend731f072011-07-11 15:59:22 -0700859#ifdef HAVE_ANDROID_OS
860pid_t Thread::getTid() const
861{
862 // mTid is not defined until the child initializes it, and the caller may need it earlier
863 Mutex::Autolock _l(mLock);
864 pid_t tid;
865 if (mRunning) {
866 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
867 tid = __pthread_gettid(pthread);
868 } else {
869 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
870 tid = -1;
871 }
872 return tid;
873}
874#endif
875
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800876bool Thread::exitPending() const
877{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800878 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800879 return mExitPending;
880}
881
882
883
884}; // namespace android