blob: 4036c497a45b35aa064f8f0ae4e663a92907fdd3 [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
23#include <stdio.h>
24#include <stdlib.h>
25#include <memory.h>
26#include <errno.h>
27#include <assert.h>
28#include <unistd.h>
29
30#if defined(HAVE_PTHREADS)
31# include <pthread.h>
32# include <sched.h>
33# include <sys/resource.h>
34#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
45/*
46 * ===========================================================================
47 * Thread wrappers
48 * ===========================================================================
49 */
50
51using namespace android;
52
53// ----------------------------------------------------------------------------
54#if defined(HAVE_PTHREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080055// ----------------------------------------------------------------------------
56
57/*
58 * Create and run a new thead.
59 *
60 * We create it "detached", so it cleans up after itself.
61 */
62
63typedef void* (*android_pthread_entry)(void*);
64
65struct thread_data_t {
66 thread_func_t entryFunction;
67 void* userData;
68 int priority;
69 char * threadName;
70
71 // we use this trampoline when we need to set the priority with
72 // nice/setpriority.
73 static int trampoline(const thread_data_t* t) {
74 thread_func_t f = t->entryFunction;
75 void* u = t->userData;
76 int prio = t->priority;
77 char * name = t->threadName;
78 delete t;
79 setpriority(PRIO_PROCESS, 0, prio);
80 if (name) {
81#if defined(HAVE_PRCTL)
82 // Mac OS doesn't have this, and we build libutil for the host too
83 int hasAt = 0;
84 int hasDot = 0;
85 char *s = name;
86 while (*s) {
87 if (*s == '.') hasDot = 1;
88 else if (*s == '@') hasAt = 1;
89 s++;
90 }
91 int len = s - name;
92 if (len < 15 || hasAt || !hasDot) {
93 s = name;
94 } else {
95 s = name + len - 15;
96 }
97 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
98#endif
99 free(name);
100 }
101 return f(u);
102 }
103};
104
105int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
106 void *userData,
107 const char* threadName,
108 int32_t threadPriority,
109 size_t threadStackSize,
110 android_thread_id_t *threadId)
111{
112 pthread_attr_t attr;
113 pthread_attr_init(&attr);
114 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
115
116#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
117 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
118 // We could avoid the trampoline if there was a way to get to the
119 // android_thread_id_t (pid) from pthread_t
120 thread_data_t* t = new thread_data_t;
121 t->priority = threadPriority;
122 t->threadName = threadName ? strdup(threadName) : NULL;
123 t->entryFunction = entryFunction;
124 t->userData = userData;
125 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
126 userData = t;
127 }
128#endif
129
130 if (threadStackSize) {
131 pthread_attr_setstacksize(&attr, threadStackSize);
132 }
133
134 errno = 0;
135 pthread_t thread;
136 int result = pthread_create(&thread, &attr,
137 (android_pthread_entry)entryFunction, userData);
138 if (result != 0) {
139 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
140 "(android threadPriority=%d)",
141 entryFunction, result, errno, threadPriority);
142 return 0;
143 }
144
145 if (threadId != NULL) {
146 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
147 }
148 return 1;
149}
150
151android_thread_id_t androidGetThreadId()
152{
153 return (android_thread_id_t)pthread_self();
154}
155
156// ----------------------------------------------------------------------------
157#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800158// ----------------------------------------------------------------------------
159
160/*
161 * Trampoline to make us __stdcall-compliant.
162 *
163 * We're expected to delete "vDetails" when we're done.
164 */
165struct threadDetails {
166 int (*func)(void*);
167 void* arg;
168};
169static __stdcall unsigned int threadIntermediary(void* vDetails)
170{
171 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
172 int result;
173
174 result = (*(pDetails->func))(pDetails->arg);
175
176 delete pDetails;
177
178 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
179 return (unsigned int) result;
180}
181
182/*
183 * Create and run a new thread.
184 */
185static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
186{
187 HANDLE hThread;
188 struct threadDetails* pDetails = new threadDetails; // must be on heap
189 unsigned int thrdaddr;
190
191 pDetails->func = fn;
192 pDetails->arg = arg;
193
194#if defined(HAVE__BEGINTHREADEX)
195 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
196 &thrdaddr);
197 if (hThread == 0)
198#elif defined(HAVE_CREATETHREAD)
199 hThread = CreateThread(NULL, 0,
200 (LPTHREAD_START_ROUTINE) threadIntermediary,
201 (void*) pDetails, 0, (DWORD*) &thrdaddr);
202 if (hThread == NULL)
203#endif
204 {
205 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
206 return false;
207 }
208
209#if defined(HAVE_CREATETHREAD)
210 /* close the management handle */
211 CloseHandle(hThread);
212#endif
213
214 if (id != NULL) {
215 *id = (android_thread_id_t)thrdaddr;
216 }
217
218 return true;
219}
220
221int androidCreateRawThreadEtc(android_thread_func_t fn,
222 void *userData,
223 const char* threadName,
224 int32_t threadPriority,
225 size_t threadStackSize,
226 android_thread_id_t *threadId)
227{
228 return doCreateThread( fn, userData, threadId);
229}
230
231android_thread_id_t androidGetThreadId()
232{
233 return (android_thread_id_t)GetCurrentThreadId();
234}
235
236// ----------------------------------------------------------------------------
237#else
238#error "Threads not supported"
239#endif
240
241// ----------------------------------------------------------------------------
242
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800243int androidCreateThread(android_thread_func_t fn, void* arg)
244{
245 return createThreadEtc(fn, arg);
246}
247
248int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
249{
250 return createThreadEtc(fn, arg, "android:unnamed_thread",
251 PRIORITY_DEFAULT, 0, id);
252}
253
254static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
255
256int androidCreateThreadEtc(android_thread_func_t entryFunction,
257 void *userData,
258 const char* threadName,
259 int32_t threadPriority,
260 size_t threadStackSize,
261 android_thread_id_t *threadId)
262{
263 return gCreateThreadFn(entryFunction, userData, threadName,
264 threadPriority, threadStackSize, threadId);
265}
266
267void androidSetCreateThreadFunc(android_create_thread_fn func)
268{
269 gCreateThreadFn = func;
270}
271
272namespace android {
273
274/*
275 * ===========================================================================
276 * Mutex class
277 * ===========================================================================
278 */
279
Mathias Agopian15554362009-07-12 23:11:20 -0700280#if defined(HAVE_PTHREADS)
281// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800282#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800283
284Mutex::Mutex()
285{
286 HANDLE hMutex;
287
288 assert(sizeof(hMutex) == sizeof(mState));
289
290 hMutex = CreateMutex(NULL, FALSE, NULL);
291 mState = (void*) hMutex;
292}
293
294Mutex::Mutex(const char* name)
295{
296 // XXX: name not used for now
297 HANDLE hMutex;
298
299 hMutex = CreateMutex(NULL, FALSE, NULL);
300 mState = (void*) hMutex;
301}
302
303Mutex::~Mutex()
304{
305 CloseHandle((HANDLE) mState);
306}
307
308status_t Mutex::lock()
309{
310 DWORD dwWaitResult;
311 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
312 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
313}
314
315void Mutex::unlock()
316{
317 if (!ReleaseMutex((HANDLE) mState))
318 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
319}
320
321status_t Mutex::tryLock()
322{
323 DWORD dwWaitResult;
324
325 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
326 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
327 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
328 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
329}
330
331#else
332#error "Somebody forgot to implement threads for this platform."
333#endif
334
335
336/*
337 * ===========================================================================
338 * Condition class
339 * ===========================================================================
340 */
341
Mathias Agopian15554362009-07-12 23:11:20 -0700342#if defined(HAVE_PTHREADS)
343// implemented as inlines in threads.h
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800344#elif defined(HAVE_WIN32_THREADS)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800345
346/*
347 * Windows doesn't have a condition variable solution. It's possible
348 * to create one, but it's easy to get it wrong. For a discussion, and
349 * the origin of this implementation, see:
350 *
351 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
352 *
353 * The implementation shown on the page does NOT follow POSIX semantics.
354 * As an optimization they require acquiring the external mutex before
355 * calling signal() and broadcast(), whereas POSIX only requires grabbing
356 * it before calling wait(). The implementation here has been un-optimized
357 * to have the correct behavior.
358 */
359typedef struct WinCondition {
360 // Number of waiting threads.
361 int waitersCount;
362
363 // Serialize access to waitersCount.
364 CRITICAL_SECTION waitersCountLock;
365
366 // Semaphore used to queue up threads waiting for the condition to
367 // become signaled.
368 HANDLE sema;
369
370 // An auto-reset event used by the broadcast/signal thread to wait
371 // for all the waiting thread(s) to wake up and be released from
372 // the semaphore.
373 HANDLE waitersDone;
374
375 // This mutex wouldn't be necessary if we required that the caller
376 // lock the external mutex before calling signal() and broadcast().
377 // I'm trying to mimic pthread semantics though.
378 HANDLE internalMutex;
379
380 // Keeps track of whether we were broadcasting or signaling. This
381 // allows us to optimize the code if we're just signaling.
382 bool wasBroadcast;
383
384 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
385 {
386 // Increment the wait count, avoiding race conditions.
387 EnterCriticalSection(&condState->waitersCountLock);
388 condState->waitersCount++;
389 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
390 // condState->waitersCount, getThreadId());
391 LeaveCriticalSection(&condState->waitersCountLock);
392
393 DWORD timeout = INFINITE;
394 if (abstime) {
395 nsecs_t reltime = *abstime - systemTime();
396 if (reltime < 0)
397 reltime = 0;
398 timeout = reltime/1000000;
399 }
400
401 // Atomically release the external mutex and wait on the semaphore.
402 DWORD res =
403 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
404
405 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
406
407 // Reacquire lock to avoid race conditions.
408 EnterCriticalSection(&condState->waitersCountLock);
409
410 // No longer waiting.
411 condState->waitersCount--;
412
413 // Check to see if we're the last waiter after a broadcast.
414 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
415
416 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
417 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
418
419 LeaveCriticalSection(&condState->waitersCountLock);
420
421 // If we're the last waiter thread during this particular broadcast
422 // then signal broadcast() that we're all awake. It'll drop the
423 // internal mutex.
424 if (lastWaiter) {
425 // Atomically signal the "waitersDone" event and wait until we
426 // can acquire the internal mutex. We want to do this in one step
427 // because it ensures that everybody is in the mutex FIFO before
428 // any thread has a chance to run. Without it, another thread
429 // could wake up, do work, and hop back in ahead of us.
430 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
431 INFINITE, FALSE);
432 } else {
433 // Grab the internal mutex.
434 WaitForSingleObject(condState->internalMutex, INFINITE);
435 }
436
437 // Release the internal and grab the external.
438 ReleaseMutex(condState->internalMutex);
439 WaitForSingleObject(hMutex, INFINITE);
440
441 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
442 }
443} WinCondition;
444
445/*
446 * Constructor. Set up the WinCondition stuff.
447 */
448Condition::Condition()
449{
450 WinCondition* condState = new WinCondition;
451
452 condState->waitersCount = 0;
453 condState->wasBroadcast = false;
454 // semaphore: no security, initial value of 0
455 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
456 InitializeCriticalSection(&condState->waitersCountLock);
457 // auto-reset event, not signaled initially
458 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
459 // used so we don't have to lock external mutex on signal/broadcast
460 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
461
462 mState = condState;
463}
464
465/*
466 * Destructor. Free Windows resources as well as our allocated storage.
467 */
468Condition::~Condition()
469{
470 WinCondition* condState = (WinCondition*) mState;
471 if (condState != NULL) {
472 CloseHandle(condState->sema);
473 CloseHandle(condState->waitersDone);
474 delete condState;
475 }
476}
477
478
479status_t Condition::wait(Mutex& mutex)
480{
481 WinCondition* condState = (WinCondition*) mState;
482 HANDLE hMutex = (HANDLE) mutex.mState;
483
484 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
485}
486
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
488{
489 return wait(mutex, systemTime()+reltime);
490}
491
492/*
493 * Signal the condition variable, allowing one thread to continue.
494 */
495void Condition::signal()
496{
497 WinCondition* condState = (WinCondition*) mState;
498
499 // Lock the internal mutex. This ensures that we don't clash with
500 // broadcast().
501 WaitForSingleObject(condState->internalMutex, INFINITE);
502
503 EnterCriticalSection(&condState->waitersCountLock);
504 bool haveWaiters = (condState->waitersCount > 0);
505 LeaveCriticalSection(&condState->waitersCountLock);
506
507 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
508 // down a notch.
509 if (haveWaiters)
510 ReleaseSemaphore(condState->sema, 1, 0);
511
512 // Release internal mutex.
513 ReleaseMutex(condState->internalMutex);
514}
515
516/*
517 * Signal the condition variable, allowing all threads to continue.
518 *
519 * First we have to wake up all threads waiting on the semaphore, then
520 * we wait until all of the threads have actually been woken before
521 * releasing the internal mutex. This ensures that all threads are woken.
522 */
523void Condition::broadcast()
524{
525 WinCondition* condState = (WinCondition*) mState;
526
527 // Lock the internal mutex. This keeps the guys we're waking up
528 // from getting too far.
529 WaitForSingleObject(condState->internalMutex, INFINITE);
530
531 EnterCriticalSection(&condState->waitersCountLock);
532 bool haveWaiters = false;
533
534 if (condState->waitersCount > 0) {
535 haveWaiters = true;
536 condState->wasBroadcast = true;
537 }
538
539 if (haveWaiters) {
540 // Wake up all the waiters.
541 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
542
543 LeaveCriticalSection(&condState->waitersCountLock);
544
545 // Wait for all awakened threads to acquire the counting semaphore.
546 // The last guy who was waiting sets this.
547 WaitForSingleObject(condState->waitersDone, INFINITE);
548
549 // Reset wasBroadcast. (No crit section needed because nobody
550 // else can wake up to poke at it.)
551 condState->wasBroadcast = 0;
552 } else {
553 // nothing to do
554 LeaveCriticalSection(&condState->waitersCountLock);
555 }
556
557 // Release internal mutex.
558 ReleaseMutex(condState->internalMutex);
559}
560
561#else
562#error "condition variables not supported on this platform"
563#endif
564
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800565// ----------------------------------------------------------------------------
566
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800567/*
568 * This is our thread object!
569 */
570
571Thread::Thread(bool canCallJava)
572 : mCanCallJava(canCallJava),
573 mThread(thread_id_t(-1)),
574 mLock("Thread::mLock"),
575 mStatus(NO_ERROR),
576 mExitPending(false), mRunning(false)
577{
578}
579
580Thread::~Thread()
581{
582}
583
584status_t Thread::readyToRun()
585{
586 return NO_ERROR;
587}
588
589status_t Thread::run(const char* name, int32_t priority, size_t stack)
590{
591 Mutex::Autolock _l(mLock);
592
593 if (mRunning) {
594 // thread already started
595 return INVALID_OPERATION;
596 }
597
598 // reset status and exitPending to their default value, so we can
599 // try again after an error happened (either below, or in readyToRun())
600 mStatus = NO_ERROR;
601 mExitPending = false;
602 mThread = thread_id_t(-1);
603
604 // hold a strong reference on ourself
605 mHoldSelf = this;
606
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800607 mRunning = true;
608
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800609 bool res;
610 if (mCanCallJava) {
611 res = createThreadEtc(_threadLoop,
612 this, name, priority, stack, &mThread);
613 } else {
614 res = androidCreateRawThreadEtc(_threadLoop,
615 this, name, priority, stack, &mThread);
616 }
617
618 if (res == false) {
619 mStatus = UNKNOWN_ERROR; // something happened!
620 mRunning = false;
621 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800622 mHoldSelf.clear(); // "this" may have gone away after this.
623
624 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800625 }
626
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800627 // Do not refer to mStatus here: The thread is already running (may, in fact
628 // already have exited with a valid mStatus result). The NO_ERROR indication
629 // here merely indicates successfully starting the thread and does not
630 // imply successful termination/execution.
631 return NO_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800632}
633
634int Thread::_threadLoop(void* user)
635{
636 Thread* const self = static_cast<Thread*>(user);
637 sp<Thread> strong(self->mHoldSelf);
638 wp<Thread> weak(strong);
639 self->mHoldSelf.clear();
640
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800641 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800642
643 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800644 bool result;
645 if (first) {
646 first = false;
647 self->mStatus = self->readyToRun();
648 result = (self->mStatus == NO_ERROR);
649
650 if (result && !self->mExitPending) {
651 // Binder threads (and maybe others) rely on threadLoop
652 // running at least once after a successful ::readyToRun()
653 // (unless, of course, the thread has already been asked to exit
654 // at that point).
655 // This is because threads are essentially used like this:
656 // (new ThreadSubclass())->run();
657 // The caller therefore does not retain a strong reference to
658 // the thread and the thread would simply disappear after the
659 // successful ::readyToRun() call instead of entering the
660 // threadLoop at least once.
661 result = self->threadLoop();
662 }
663 } else {
664 result = self->threadLoop();
665 }
666
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800667 if (result == false || self->mExitPending) {
668 self->mExitPending = true;
669 self->mLock.lock();
670 self->mRunning = false;
671 self->mThreadExitedCondition.signal();
672 self->mLock.unlock();
673 break;
674 }
675
676 // Release our strong reference, to let a chance to the thread
677 // to die a peaceful death.
678 strong.clear();
679 // And immediately, reacquire a strong reference for the next loop
680 strong = weak.promote();
681 } while(strong != 0);
682
683 return 0;
684}
685
686void Thread::requestExit()
687{
688 mExitPending = true;
689}
690
691status_t Thread::requestExitAndWait()
692{
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800693 if (mThread == getThreadId()) {
694 LOGW(
695 "Thread (this=%p): don't call waitForExit() from this "
696 "Thread object's thread. It's a guaranteed deadlock!",
697 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800698
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800699 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800700 }
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800701
702 requestExit();
703
704 Mutex::Autolock _l(mLock);
705 while (mRunning == true) {
706 mThreadExitedCondition.wait(mLock);
707 }
708 mExitPending = false;
709
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800710 return mStatus;
711}
712
713bool Thread::exitPending() const
714{
715 return mExitPending;
716}
717
718
719
720}; // namespace android