123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857 |
- #define LOG_TAG "libutils.threads"
- #include <assert.h>
- #include <utils/Thread.h>
- #include <utils/AndroidThreads.h>
- #if !defined(_WIN32)
- # include <sys/resource.h>
- #else
- # include <windows.h>
- # include <stdint.h>
- # include <process.h>
- # define HAVE_CREATETHREAD
- #endif
- #if defined(__linux__)
- #include <sys/prctl.h>
- #endif
- #include <utils/Log.h>
- #include <processgroup/sched_policy.h>
- #if defined(__ANDROID__)
- # define __android_unused
- #else
- # define __android_unused __attribute__((__unused__))
- #endif
- using namespace android;
- #if !defined(_WIN32)
- typedef void* (*android_pthread_entry)(void*);
- struct thread_data_t {
- thread_func_t entryFunction;
- void* userData;
- int priority;
- char * threadName;
-
-
- static int trampoline(const thread_data_t* t) {
- thread_func_t f = t->entryFunction;
- void* u = t->userData;
- int prio = t->priority;
- char * name = t->threadName;
- delete t;
- setpriority(PRIO_PROCESS, 0, prio);
- if (prio >= ANDROID_PRIORITY_BACKGROUND) {
- set_sched_policy(0, SP_BACKGROUND);
- } else {
- set_sched_policy(0, SP_FOREGROUND);
- }
- if (name) {
- androidSetThreadName(name);
- free(name);
- }
- return f(u);
- }
- };
- void androidSetThreadName(const char* name) {
- #if defined(__linux__)
-
- int hasAt = 0;
- int hasDot = 0;
- const char *s = name;
- while (*s) {
- if (*s == '.') hasDot = 1;
- else if (*s == '@') hasAt = 1;
- s++;
- }
- int len = s - name;
- if (len < 15 || hasAt || !hasDot) {
- s = name;
- } else {
- s = name + len - 15;
- }
- prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
- #endif
- }
- int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
- void *userData,
- const char* threadName __android_unused,
- int32_t threadPriority,
- size_t threadStackSize,
- android_thread_id_t *threadId)
- {
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
- #if defined(__ANDROID__)
- if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
-
-
-
-
-
-
-
- thread_data_t* t = new thread_data_t;
- t->priority = threadPriority;
- t->threadName = threadName ? strdup(threadName) : NULL;
- t->entryFunction = entryFunction;
- t->userData = userData;
- entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
- userData = t;
- }
- #endif
- if (threadStackSize) {
- pthread_attr_setstacksize(&attr, threadStackSize);
- }
- errno = 0;
- pthread_t thread;
- int result = pthread_create(&thread, &attr,
- (android_pthread_entry)entryFunction, userData);
- pthread_attr_destroy(&attr);
- if (result != 0) {
- ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
- "(android threadPriority=%d)",
- entryFunction, result, strerror(errno), threadPriority);
- return 0;
- }
-
-
-
- if (threadId != nullptr) {
- *threadId = (android_thread_id_t)thread;
- }
- return 1;
- }
- #if defined(__ANDROID__)
- static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
- {
- return (pthread_t) thread;
- }
- #endif
- android_thread_id_t androidGetThreadId()
- {
- return (android_thread_id_t)pthread_self();
- }
- #else
- struct threadDetails {
- int (*func)(void*);
- void* arg;
- };
- static __stdcall unsigned int threadIntermediary(void* vDetails)
- {
- struct threadDetails* pDetails = (struct threadDetails*) vDetails;
- int result;
- result = (*(pDetails->func))(pDetails->arg);
- delete pDetails;
- ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
- return (unsigned int) result;
- }
- static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
- {
- HANDLE hThread;
- struct threadDetails* pDetails = new threadDetails;
- unsigned int thrdaddr;
- pDetails->func = fn;
- pDetails->arg = arg;
- #if defined(HAVE__BEGINTHREADEX)
- hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
- &thrdaddr);
- if (hThread == 0)
- #elif defined(HAVE_CREATETHREAD)
- hThread = CreateThread(NULL, 0,
- (LPTHREAD_START_ROUTINE) threadIntermediary,
- (void*) pDetails, 0, (DWORD*) &thrdaddr);
- if (hThread == NULL)
- #endif
- {
- ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
- return false;
- }
- #if defined(HAVE_CREATETHREAD)
-
- CloseHandle(hThread);
- #endif
- if (id != NULL) {
- *id = (android_thread_id_t)thrdaddr;
- }
- return true;
- }
- int androidCreateRawThreadEtc(android_thread_func_t fn,
- void *userData,
- const char* ,
- int32_t ,
- size_t ,
- android_thread_id_t *threadId)
- {
- return doCreateThread( fn, userData, threadId);
- }
- android_thread_id_t androidGetThreadId()
- {
- return (android_thread_id_t)GetCurrentThreadId();
- }
- #endif
- int androidCreateThread(android_thread_func_t fn, void* arg)
- {
- return createThreadEtc(fn, arg);
- }
- int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
- {
- return createThreadEtc(fn, arg, "android:unnamed_thread",
- PRIORITY_DEFAULT, 0, id);
- }
- static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
- int androidCreateThreadEtc(android_thread_func_t entryFunction,
- void *userData,
- const char* threadName,
- int32_t threadPriority,
- size_t threadStackSize,
- android_thread_id_t *threadId)
- {
- return gCreateThreadFn(entryFunction, userData, threadName,
- threadPriority, threadStackSize, threadId);
- }
- void androidSetCreateThreadFunc(android_create_thread_fn func)
- {
- gCreateThreadFn = func;
- }
- #if defined(__ANDROID__)
- int androidSetThreadPriority(pid_t tid, int pri)
- {
- int rc = 0;
- int lasterr = 0;
- if (pri >= ANDROID_PRIORITY_BACKGROUND) {
- rc = set_sched_policy(tid, SP_BACKGROUND);
- } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
- rc = set_sched_policy(tid, SP_FOREGROUND);
- }
- if (rc) {
- lasterr = errno;
- }
- if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
- rc = INVALID_OPERATION;
- } else {
- errno = lasterr;
- }
- return rc;
- }
- int androidGetThreadPriority(pid_t tid) {
- return getpriority(PRIO_PROCESS, tid);
- }
- #endif
- namespace android {
- #if !defined(_WIN32)
- #else
- Mutex::Mutex()
- {
- HANDLE hMutex;
- assert(sizeof(hMutex) == sizeof(mState));
- hMutex = CreateMutex(NULL, FALSE, NULL);
- mState = (void*) hMutex;
- }
- Mutex::Mutex(const char* )
- {
-
- HANDLE hMutex;
- assert(sizeof(hMutex) == sizeof(mState));
- hMutex = CreateMutex(NULL, FALSE, NULL);
- mState = (void*) hMutex;
- }
- Mutex::Mutex(int , const char* )
- {
-
- HANDLE hMutex;
- assert(sizeof(hMutex) == sizeof(mState));
- hMutex = CreateMutex(NULL, FALSE, NULL);
- mState = (void*) hMutex;
- }
- Mutex::~Mutex()
- {
- CloseHandle((HANDLE) mState);
- }
- status_t Mutex::lock()
- {
- DWORD dwWaitResult;
- dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
- return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
- }
- void Mutex::unlock()
- {
- if (!ReleaseMutex((HANDLE) mState))
- ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
- }
- status_t Mutex::tryLock()
- {
- DWORD dwWaitResult;
- dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
- if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
- ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
- return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
- }
- #endif
- #if !defined(_WIN32)
- #else
- typedef struct WinCondition {
-
- int waitersCount;
-
- CRITICAL_SECTION waitersCountLock;
-
-
- HANDLE sema;
-
-
-
- HANDLE waitersDone;
-
-
-
- HANDLE internalMutex;
-
-
- bool wasBroadcast;
- status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
- {
-
- EnterCriticalSection(&condState->waitersCountLock);
- condState->waitersCount++;
-
-
- LeaveCriticalSection(&condState->waitersCountLock);
- DWORD timeout = INFINITE;
- if (abstime) {
- nsecs_t reltime = *abstime - systemTime();
- if (reltime < 0)
- reltime = 0;
- timeout = reltime/1000000;
- }
-
- DWORD res =
- SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
-
-
- EnterCriticalSection(&condState->waitersCountLock);
-
- condState->waitersCount--;
-
- bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
-
-
- LeaveCriticalSection(&condState->waitersCountLock);
-
-
-
- if (lastWaiter) {
-
-
-
-
-
- SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
- INFINITE, FALSE);
- } else {
-
- WaitForSingleObject(condState->internalMutex, INFINITE);
- }
-
- ReleaseMutex(condState->internalMutex);
- WaitForSingleObject(hMutex, INFINITE);
- return res == WAIT_OBJECT_0 ? OK : -1;
- }
- } WinCondition;
- Condition::Condition()
- {
- WinCondition* condState = new WinCondition;
- condState->waitersCount = 0;
- condState->wasBroadcast = false;
-
- condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
- InitializeCriticalSection(&condState->waitersCountLock);
-
- condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
-
- condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
- mState = condState;
- }
- Condition::~Condition()
- {
- WinCondition* condState = (WinCondition*) mState;
- if (condState != NULL) {
- CloseHandle(condState->sema);
- CloseHandle(condState->waitersDone);
- delete condState;
- }
- }
- status_t Condition::wait(Mutex& mutex)
- {
- WinCondition* condState = (WinCondition*) mState;
- HANDLE hMutex = (HANDLE) mutex.mState;
- return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
- }
- status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
- {
- WinCondition* condState = (WinCondition*) mState;
- HANDLE hMutex = (HANDLE) mutex.mState;
- nsecs_t absTime = systemTime()+reltime;
- return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
- }
- void Condition::signal()
- {
- WinCondition* condState = (WinCondition*) mState;
-
-
- WaitForSingleObject(condState->internalMutex, INFINITE);
- EnterCriticalSection(&condState->waitersCountLock);
- bool haveWaiters = (condState->waitersCount > 0);
- LeaveCriticalSection(&condState->waitersCountLock);
-
-
- if (haveWaiters)
- ReleaseSemaphore(condState->sema, 1, 0);
-
- ReleaseMutex(condState->internalMutex);
- }
- void Condition::broadcast()
- {
- WinCondition* condState = (WinCondition*) mState;
-
-
- WaitForSingleObject(condState->internalMutex, INFINITE);
- EnterCriticalSection(&condState->waitersCountLock);
- bool haveWaiters = false;
- if (condState->waitersCount > 0) {
- haveWaiters = true;
- condState->wasBroadcast = true;
- }
- if (haveWaiters) {
-
- ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
- LeaveCriticalSection(&condState->waitersCountLock);
-
-
- WaitForSingleObject(condState->waitersDone, INFINITE);
-
-
- condState->wasBroadcast = 0;
- } else {
-
- LeaveCriticalSection(&condState->waitersCountLock);
- }
-
- ReleaseMutex(condState->internalMutex);
- }
- #endif
- Thread::Thread(bool canCallJava)
- : mCanCallJava(canCallJava),
- mThread(thread_id_t(-1)),
- mLock("Thread::mLock"),
- mStatus(OK),
- mExitPending(false),
- mRunning(false)
- #if defined(__ANDROID__)
- ,
- mTid(-1)
- #endif
- {
- }
- Thread::~Thread()
- {
- }
- status_t Thread::readyToRun()
- {
- return OK;
- }
- status_t Thread::run(const char* name, int32_t priority, size_t stack)
- {
- LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
- Mutex::Autolock _l(mLock);
- if (mRunning) {
-
- return INVALID_OPERATION;
- }
-
-
- mStatus = OK;
- mExitPending = false;
- mThread = thread_id_t(-1);
-
- mHoldSelf = this;
- mRunning = true;
- bool res;
- if (mCanCallJava) {
- res = createThreadEtc(_threadLoop,
- this, name, priority, stack, &mThread);
- } else {
- res = androidCreateRawThreadEtc(_threadLoop,
- this, name, priority, stack, &mThread);
- }
- if (res == false) {
- mStatus = UNKNOWN_ERROR;
- mRunning = false;
- mThread = thread_id_t(-1);
- mHoldSelf.clear();
- return UNKNOWN_ERROR;
- }
-
-
-
-
- return OK;
-
- }
- int Thread::_threadLoop(void* user)
- {
- Thread* const self = static_cast<Thread*>(user);
- sp<Thread> strong(self->mHoldSelf);
- wp<Thread> weak(strong);
- self->mHoldSelf.clear();
- #if defined(__ANDROID__)
-
- self->mTid = gettid();
- #endif
- bool first = true;
- do {
- bool result;
- if (first) {
- first = false;
- self->mStatus = self->readyToRun();
- result = (self->mStatus == OK);
- if (result && !self->exitPending()) {
-
-
-
-
-
-
-
-
-
-
- result = self->threadLoop();
- }
- } else {
- result = self->threadLoop();
- }
-
- {
- Mutex::Autolock _l(self->mLock);
- if (result == false || self->mExitPending) {
- self->mExitPending = true;
- self->mRunning = false;
-
-
- self->mThread = thread_id_t(-1);
-
-
- self->mThreadExitedCondition.broadcast();
- break;
- }
- }
-
-
- strong.clear();
-
- strong = weak.promote();
- } while(strong != nullptr);
- return 0;
- }
- void Thread::requestExit()
- {
- Mutex::Autolock _l(mLock);
- mExitPending = true;
- }
- status_t Thread::requestExitAndWait()
- {
- Mutex::Autolock _l(mLock);
- if (mThread == getThreadId()) {
- ALOGW(
- "Thread (this=%p): don't call waitForExit() from this "
- "Thread object's thread. It's a guaranteed deadlock!",
- this);
- return WOULD_BLOCK;
- }
- mExitPending = true;
- while (mRunning == true) {
- mThreadExitedCondition.wait(mLock);
- }
-
-
- mExitPending = false;
- return mStatus;
- }
- status_t Thread::join()
- {
- Mutex::Autolock _l(mLock);
- if (mThread == getThreadId()) {
- ALOGW(
- "Thread (this=%p): don't call join() from this "
- "Thread object's thread. It's a guaranteed deadlock!",
- this);
- return WOULD_BLOCK;
- }
- while (mRunning == true) {
- mThreadExitedCondition.wait(mLock);
- }
- return mStatus;
- }
- bool Thread::isRunning() const {
- Mutex::Autolock _l(mLock);
- return mRunning;
- }
- #if defined(__ANDROID__)
- pid_t Thread::getTid() const
- {
-
- Mutex::Autolock _l(mLock);
- pid_t tid;
- if (mRunning) {
- pthread_t pthread = android_thread_id_t_to_pthread(mThread);
- tid = pthread_gettid_np(pthread);
- } else {
- ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
- tid = -1;
- }
- return tid;
- }
- #endif
- bool Thread::exitPending() const
- {
- Mutex::Autolock _l(mLock);
- return mExitPending;
- }
- };
|