2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // #define LOG_NDEBUG 0
18 #define LOG_TAG "libutils.threads"
20 #include <utils/threads.h>
21 #include <utils/Log.h>
23 #include <cutils/sched_policy.h>
24 #include <cutils/properties.h>
33 #if defined(HAVE_PTHREADS)
36 # include <sys/resource.h>
37 #elif defined(HAVE_WIN32_THREADS)
41 # define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
44 #if defined(HAVE_PRCTL)
45 #include <sys/prctl.h>
49 * ===========================================================================
51 * ===========================================================================
54 using namespace android;
56 // ----------------------------------------------------------------------------
57 #if defined(HAVE_PTHREADS)
58 // ----------------------------------------------------------------------------
61 * Create and run a new thread.
63 * We create it "detached", so it cleans up after itself.
66 typedef void* (*android_pthread_entry)(void*);
68 static pthread_once_t gDoSchedulingGroupOnce = PTHREAD_ONCE_INIT;
69 static bool gDoSchedulingGroup = true;
71 static void checkDoSchedulingGroup(void) {
72 char buf[PROPERTY_VALUE_MAX];
73 int len = property_get("debug.sys.noschedgroups", buf, "");
76 if (sscanf(buf, "%d", &temp) == 1) {
77 gDoSchedulingGroup = temp == 0;
82 struct thread_data_t {
83 thread_func_t entryFunction;
88 // we use this trampoline when we need to set the priority with
90 static int trampoline(const thread_data_t* t) {
91 thread_func_t f = t->entryFunction;
92 void* u = t->userData;
93 int prio = t->priority;
94 char * name = t->threadName;
96 setpriority(PRIO_PROCESS, 0, prio);
97 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
98 if (gDoSchedulingGroup) {
99 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
100 set_sched_policy(androidGetTid(), SP_BACKGROUND);
102 set_sched_policy(androidGetTid(), SP_FOREGROUND);
107 #if defined(HAVE_PRCTL)
108 // Mac OS doesn't have this, and we build libutil for the host too
113 if (*s == '.') hasDot = 1;
114 else if (*s == '@') hasAt = 1;
118 if (len < 15 || hasAt || !hasDot) {
123 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
131 int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
133 const char* threadName,
134 int32_t threadPriority,
135 size_t threadStackSize,
136 android_thread_id_t *threadId)
139 pthread_attr_init(&attr);
140 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
142 #ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
143 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
144 // We could avoid the trampoline if there was a way to get to the
145 // android_thread_id_t (pid) from pthread_t
146 thread_data_t* t = new thread_data_t;
147 t->priority = threadPriority;
148 t->threadName = threadName ? strdup(threadName) : NULL;
149 t->entryFunction = entryFunction;
150 t->userData = userData;
151 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
156 if (threadStackSize) {
157 pthread_attr_setstacksize(&attr, threadStackSize);
162 int result = pthread_create(&thread, &attr,
163 (android_pthread_entry)entryFunction, userData);
165 LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
166 "(android threadPriority=%d)",
167 entryFunction, result, errno, threadPriority);
171 if (threadId != NULL) {
172 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
177 android_thread_id_t androidGetThreadId()
179 return (android_thread_id_t)pthread_self();
182 // ----------------------------------------------------------------------------
183 #elif defined(HAVE_WIN32_THREADS)
184 // ----------------------------------------------------------------------------
187 * Trampoline to make us __stdcall-compliant.
189 * We're expected to delete "vDetails" when we're done.
191 struct threadDetails {
195 static __stdcall unsigned int threadIntermediary(void* vDetails)
197 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
200 result = (*(pDetails->func))(pDetails->arg);
204 LOG(LOG_VERBOSE, "thread", "thread exiting\n");
205 return (unsigned int) result;
209 * Create and run a new thread.
211 static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
214 struct threadDetails* pDetails = new threadDetails; // must be on heap
215 unsigned int thrdaddr;
220 #if defined(HAVE__BEGINTHREADEX)
221 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
224 #elif defined(HAVE_CREATETHREAD)
225 hThread = CreateThread(NULL, 0,
226 (LPTHREAD_START_ROUTINE) threadIntermediary,
227 (void*) pDetails, 0, (DWORD*) &thrdaddr);
231 LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
235 #if defined(HAVE_CREATETHREAD)
236 /* close the management handle */
237 CloseHandle(hThread);
241 *id = (android_thread_id_t)thrdaddr;
247 int androidCreateRawThreadEtc(android_thread_func_t fn,
249 const char* threadName,
250 int32_t threadPriority,
251 size_t threadStackSize,
252 android_thread_id_t *threadId)
254 return doCreateThread( fn, userData, threadId);
257 android_thread_id_t androidGetThreadId()
259 return (android_thread_id_t)GetCurrentThreadId();
262 // ----------------------------------------------------------------------------
264 #error "Threads not supported"
267 // ----------------------------------------------------------------------------
269 int androidCreateThread(android_thread_func_t fn, void* arg)
271 return createThreadEtc(fn, arg);
274 int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
276 return createThreadEtc(fn, arg, "android:unnamed_thread",
277 PRIORITY_DEFAULT, 0, id);
280 static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
282 int androidCreateThreadEtc(android_thread_func_t entryFunction,
284 const char* threadName,
285 int32_t threadPriority,
286 size_t threadStackSize,
287 android_thread_id_t *threadId)
289 return gCreateThreadFn(entryFunction, userData, threadName,
290 threadPriority, threadStackSize, threadId);
293 void androidSetCreateThreadFunc(android_create_thread_fn func)
295 gCreateThreadFn = func;
298 pid_t androidGetTid()
307 int androidSetThreadSchedulingGroup(pid_t tid, int grp)
309 if (grp > ANDROID_TGROUP_MAX || grp < 0) {
313 #if defined(HAVE_PTHREADS)
314 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
315 if (gDoSchedulingGroup) {
316 if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
317 SP_BACKGROUND : SP_FOREGROUND)) {
318 return PERMISSION_DENIED;
326 int androidSetThreadPriority(pid_t tid, int pri)
330 #if defined(HAVE_PTHREADS)
333 pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
334 if (gDoSchedulingGroup) {
335 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
336 rc = set_sched_policy(tid, SP_BACKGROUND);
337 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
338 rc = set_sched_policy(tid, SP_FOREGROUND);
346 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
347 rc = INVALID_OPERATION;
359 * ===========================================================================
361 * ===========================================================================
364 #if defined(HAVE_PTHREADS)
365 Condition::Condition() {
366 pthread_cond_init(&mCond, NULL);
368 Condition::Condition(int type) {
369 if (type == SHARED) {
370 pthread_condattr_t attr;
371 pthread_condattr_init(&attr);
372 pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
373 pthread_cond_init(&mCond, &attr);
374 pthread_condattr_destroy(&attr);
376 pthread_cond_init(&mCond, NULL);
379 Condition::~Condition() {
380 pthread_cond_destroy(&mCond);
382 status_t Condition::wait(Mutex& mutex) {
383 return -pthread_cond_wait(&mCond, &mutex.mMutex);
385 status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
386 #if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
388 ts.tv_sec = reltime/1000000000;
389 ts.tv_nsec = reltime%1000000000;
390 return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
391 #else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
393 #if defined(HAVE_POSIX_CLOCKS)
394 clock_gettime(CLOCK_REALTIME, &ts);
395 #else // HAVE_POSIX_CLOCKS
396 // we don't support the clocks here.
398 gettimeofday(&t, NULL);
399 ts.tv_sec = t.tv_sec;
400 ts.tv_nsec= t.tv_usec*1000;
401 #endif // HAVE_POSIX_CLOCKS
402 ts.tv_sec += reltime/1000000000;
403 ts.tv_nsec+= reltime%1000000000;
404 if (ts.tv_nsec >= 1000000000) {
405 ts.tv_nsec -= 1000000000;
408 return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
409 #endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
411 void Condition::signal() {
412 pthread_cond_signal(&mCond);
414 void Condition::broadcast() {
415 pthread_cond_broadcast(&mCond);
418 #elif defined(HAVE_WIN32_THREADS)
422 assert(sizeof(hMutex) == sizeof(mState));
423 hMutex = CreateMutex(NULL, FALSE, NULL);
424 mState = (void*) hMutex;
426 Mutex::Mutex(const char* name)
428 // XXX: name not used for now
430 assert(sizeof(hMutex) == sizeof(mState));
431 hMutex = CreateMutex(NULL, FALSE, NULL);
432 mState = (void*) hMutex;
435 Mutex::Mutex(int type, const char* name)
437 // XXX: type and name not used for now
440 assert(sizeof(hMutex) == sizeof(mState));
442 hMutex = CreateMutex(NULL, FALSE, NULL);
443 mState = (void*) hMutex;
448 CloseHandle((HANDLE) mState);
451 status_t Mutex::lock()
454 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
455 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
460 if (!ReleaseMutex((HANDLE) mState))
461 LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
464 status_t Mutex::tryLock()
468 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
469 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
470 LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
471 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
475 #error "Somebody forgot to implement threads for this platform."
480 * ===========================================================================
482 * ===========================================================================
485 #if defined(HAVE_PTHREADS)
487 pthread_mutex_init(&mMutex, NULL);
489 Mutex::Mutex(const char* name) {
490 pthread_mutex_init(&mMutex, NULL);
492 Mutex::Mutex(int type, const char* name) {
493 if (type == SHARED) {
494 pthread_mutexattr_t attr;
495 pthread_mutexattr_init(&attr);
496 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
497 pthread_mutex_init(&mMutex, &attr);
498 pthread_mutexattr_destroy(&attr);
500 pthread_mutex_init(&mMutex, NULL);
504 pthread_mutex_destroy(&mMutex);
506 status_t Mutex::lock() {
507 return -pthread_mutex_lock(&mMutex);
509 void Mutex::unlock() {
510 pthread_mutex_unlock(&mMutex);
512 status_t Mutex::tryLock() {
513 return -pthread_mutex_trylock(&mMutex);
517 #elif defined(HAVE_WIN32_THREADS)
520 * Windows doesn't have a condition variable solution. It's possible
521 * to create one, but it's easy to get it wrong. For a discussion, and
522 * the origin of this implementation, see:
524 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
526 * The implementation shown on the page does NOT follow POSIX semantics.
527 * As an optimization they require acquiring the external mutex before
528 * calling signal() and broadcast(), whereas POSIX only requires grabbing
529 * it before calling wait(). The implementation here has been un-optimized
530 * to have the correct behavior.
532 typedef struct WinCondition {
533 // Number of waiting threads.
536 // Serialize access to waitersCount.
537 CRITICAL_SECTION waitersCountLock;
539 // Semaphore used to queue up threads waiting for the condition to
543 // An auto-reset event used by the broadcast/signal thread to wait
544 // for all the waiting thread(s) to wake up and be released from
548 // This mutex wouldn't be necessary if we required that the caller
549 // lock the external mutex before calling signal() and broadcast().
550 // I'm trying to mimic pthread semantics though.
551 HANDLE internalMutex;
553 // Keeps track of whether we were broadcasting or signaling. This
554 // allows us to optimize the code if we're just signaling.
557 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
559 // Increment the wait count, avoiding race conditions.
560 EnterCriticalSection(&condState->waitersCountLock);
561 condState->waitersCount++;
562 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
563 // condState->waitersCount, getThreadId());
564 LeaveCriticalSection(&condState->waitersCountLock);
566 DWORD timeout = INFINITE;
568 nsecs_t reltime = *abstime - systemTime();
571 timeout = reltime/1000000;
574 // Atomically release the external mutex and wait on the semaphore.
576 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
578 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
580 // Reacquire lock to avoid race conditions.
581 EnterCriticalSection(&condState->waitersCountLock);
583 // No longer waiting.
584 condState->waitersCount--;
586 // Check to see if we're the last waiter after a broadcast.
587 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
589 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
590 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
592 LeaveCriticalSection(&condState->waitersCountLock);
594 // If we're the last waiter thread during this particular broadcast
595 // then signal broadcast() that we're all awake. It'll drop the
598 // Atomically signal the "waitersDone" event and wait until we
599 // can acquire the internal mutex. We want to do this in one step
600 // because it ensures that everybody is in the mutex FIFO before
601 // any thread has a chance to run. Without it, another thread
602 // could wake up, do work, and hop back in ahead of us.
603 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
606 // Grab the internal mutex.
607 WaitForSingleObject(condState->internalMutex, INFINITE);
610 // Release the internal and grab the external.
611 ReleaseMutex(condState->internalMutex);
612 WaitForSingleObject(hMutex, INFINITE);
614 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
619 * Constructor. Set up the WinCondition stuff.
621 Condition::Condition()
623 WinCondition* condState = new WinCondition;
625 condState->waitersCount = 0;
626 condState->wasBroadcast = false;
627 // semaphore: no security, initial value of 0
628 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
629 InitializeCriticalSection(&condState->waitersCountLock);
630 // auto-reset event, not signaled initially
631 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
632 // used so we don't have to lock external mutex on signal/broadcast
633 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
639 * Destructor. Free Windows resources as well as our allocated storage.
641 Condition::~Condition()
643 WinCondition* condState = (WinCondition*) mState;
644 if (condState != NULL) {
645 CloseHandle(condState->sema);
646 CloseHandle(condState->waitersDone);
652 status_t Condition::wait(Mutex& mutex)
654 WinCondition* condState = (WinCondition*) mState;
655 HANDLE hMutex = (HANDLE) mutex.mState;
657 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
660 status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
662 WinCondition* condState = (WinCondition*) mState;
663 HANDLE hMutex = (HANDLE) mutex.mState;
664 nsecs_t absTime = systemTime()+reltime;
666 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
670 * Signal the condition variable, allowing one thread to continue.
672 void Condition::signal()
674 WinCondition* condState = (WinCondition*) mState;
676 // Lock the internal mutex. This ensures that we don't clash with
678 WaitForSingleObject(condState->internalMutex, INFINITE);
680 EnterCriticalSection(&condState->waitersCountLock);
681 bool haveWaiters = (condState->waitersCount > 0);
682 LeaveCriticalSection(&condState->waitersCountLock);
684 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
687 ReleaseSemaphore(condState->sema, 1, 0);
689 // Release internal mutex.
690 ReleaseMutex(condState->internalMutex);
694 * Signal the condition variable, allowing all threads to continue.
696 * First we have to wake up all threads waiting on the semaphore, then
697 * we wait until all of the threads have actually been woken before
698 * releasing the internal mutex. This ensures that all threads are woken.
700 void Condition::broadcast()
702 WinCondition* condState = (WinCondition*) mState;
704 // Lock the internal mutex. This keeps the guys we're waking up
705 // from getting too far.
706 WaitForSingleObject(condState->internalMutex, INFINITE);
708 EnterCriticalSection(&condState->waitersCountLock);
709 bool haveWaiters = false;
711 if (condState->waitersCount > 0) {
713 condState->wasBroadcast = true;
717 // Wake up all the waiters.
718 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
720 LeaveCriticalSection(&condState->waitersCountLock);
722 // Wait for all awakened threads to acquire the counting semaphore.
723 // The last guy who was waiting sets this.
724 WaitForSingleObject(condState->waitersDone, INFINITE);
726 // Reset wasBroadcast. (No crit section needed because nobody
727 // else can wake up to poke at it.)
728 condState->wasBroadcast = 0;
731 LeaveCriticalSection(&condState->waitersCountLock);
734 // Release internal mutex.
735 ReleaseMutex(condState->internalMutex);
739 #error "condition variables not supported on this platform"
742 // ----------------------------------------------------------------------------
745 * This is our thread object!
748 Thread::Thread(bool canCallJava)
749 : mCanCallJava(canCallJava),
750 mThread(thread_id_t(-1)),
751 mLock("Thread::mLock"),
753 mExitPending(false), mRunning(false)
761 status_t Thread::readyToRun()
766 status_t Thread::run(const char* name, int32_t priority, size_t stack)
768 Mutex::Autolock _l(mLock);
771 // thread already started
772 return INVALID_OPERATION;
775 // reset status and exitPending to their default value, so we can
776 // try again after an error happened (either below, or in readyToRun())
778 mExitPending = false;
779 mThread = thread_id_t(-1);
781 // hold a strong reference on ourself
788 res = createThreadEtc(_threadLoop,
789 this, name, priority, stack, &mThread);
791 res = androidCreateRawThreadEtc(_threadLoop,
792 this, name, priority, stack, &mThread);
796 mStatus = UNKNOWN_ERROR; // something happened!
798 mThread = thread_id_t(-1);
799 mHoldSelf.clear(); // "this" may have gone away after this.
801 return UNKNOWN_ERROR;
804 // 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.
811 int Thread::_threadLoop(void* user)
813 Thread* const self = static_cast<Thread*>(user);
814 sp<Thread> strong(self->mHoldSelf);
815 wp<Thread> weak(strong);
816 self->mHoldSelf.clear();
819 // this is very useful for debugging with gdb
820 self->mTid = gettid();
829 self->mStatus = self->readyToRun();
830 result = (self->mStatus == NO_ERROR);
832 if (result && !self->mExitPending) {
833 // Binder threads (and maybe others) rely on threadLoop
834 // running at least once after a successful ::readyToRun()
835 // (unless, of course, the thread has already been asked to exit
837 // This is because threads are essentially used like this:
838 // (new ThreadSubclass())->run();
839 // The caller therefore does not retain a strong reference to
840 // the thread and the thread would simply disappear after the
841 // successful ::readyToRun() call instead of entering the
842 // threadLoop at least once.
843 result = self->threadLoop();
846 result = self->threadLoop();
849 if (result == false || self->mExitPending) {
850 self->mExitPending = true;
852 self->mRunning = false;
853 self->mThreadExitedCondition.broadcast();
854 self->mThread = thread_id_t(-1); // thread id could be reused
855 self->mLock.unlock();
859 // Release our strong reference, to let a chance to the thread
860 // to die a peaceful death.
862 // And immediately, re-acquire a strong reference for the next loop
863 strong = weak.promote();
864 } while(strong != 0);
869 void Thread::requestExit()
874 status_t Thread::requestExitAndWait()
876 if (mThread == getThreadId()) {
878 "Thread (this=%p): don't call waitForExit() from this "
879 "Thread object's thread. It's a guaranteed deadlock!",
887 Mutex::Autolock _l(mLock);
888 while (mRunning == true) {
889 mThreadExitedCondition.wait(mLock);
891 mExitPending = false;
896 bool Thread::exitPending() const
903 }; // namespace android