Threads.cpp 24 KB

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