blob: c3666e4b4b7cf726748d5b876111be28004fcad1 [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>
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070025#include <string.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080026#include <unistd.h>
27
Yabin Cui4a6e5a32015-01-26 19:48:54 -080028#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080029# include <pthread.h>
30# include <sched.h>
31# include <sys/resource.h>
Yabin Cui4a6e5a32015-01-26 19:48:54 -080032#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080033# include <windows.h>
34# include <stdint.h>
35# include <process.h>
36# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
37#endif
38
Elliott Hughes292ccd32014-12-15 12:52:53 -080039#if defined(__linux__)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080040#include <sys/prctl.h>
41#endif
42
Mark Salyzyn5bed8032014-04-30 11:10:46 -070043#include <utils/threads.h>
44#include <utils/Log.h>
45
46#include <cutils/sched_policy.h>
47
48#ifdef HAVE_ANDROID_OS
49# define __android_unused
50#else
51# define __android_unused __attribute__((__unused__))
52#endif
53
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080054/*
55 * ===========================================================================
56 * Thread wrappers
57 * ===========================================================================
58 */
59
60using namespace android;
61
62// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -080063#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080064// ----------------------------------------------------------------------------
65
66/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070067 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080068 *
69 * We create it "detached", so it cleans up after itself.
70 */
71
72typedef void* (*android_pthread_entry)(void*);
73
74struct thread_data_t {
75 thread_func_t entryFunction;
76 void* userData;
77 int priority;
78 char * threadName;
79
80 // we use this trampoline when we need to set the priority with
Glenn Kastend731f072011-07-11 15:59:22 -070081 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080082 static int trampoline(const thread_data_t* t) {
83 thread_func_t f = t->entryFunction;
84 void* u = t->userData;
85 int prio = t->priority;
86 char * name = t->threadName;
87 delete t;
88 setpriority(PRIO_PROCESS, 0, prio);
Glenn Kastenfe34e452012-04-30 16:03:30 -070089 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
90 set_sched_policy(0, SP_BACKGROUND);
91 } else {
92 set_sched_policy(0, SP_FOREGROUND);
Dianne Hackborna78bab02010-09-09 15:50:18 -070093 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -080094
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080095 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080096 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080097 free(name);
98 }
99 return f(u);
100 }
101};
102
Mathias Agopian6090df82013-03-07 15:34:28 -0800103void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -0800104#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -0800105 // Mac OS doesn't have this, and we build libutil for the host too
106 int hasAt = 0;
107 int hasDot = 0;
108 const char *s = name;
109 while (*s) {
110 if (*s == '.') hasDot = 1;
111 else if (*s == '@') hasAt = 1;
112 s++;
113 }
114 int len = s - name;
115 if (len < 15 || hasAt || !hasDot) {
116 s = name;
117 } else {
118 s = name + len - 15;
119 }
120 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
121#endif
122}
123
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800124int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
125 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700126 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800127 int32_t threadPriority,
128 size_t threadStackSize,
129 android_thread_id_t *threadId)
130{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800131 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800132 pthread_attr_init(&attr);
133 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
134
135#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
136 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700137 // Now that the pthread_t has a method to find the associated
138 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
139 // this trampoline in some cases as the parent could set the properties
140 // for the child. However, there would be a race condition because the
141 // child becomes ready immediately, and it doesn't work for the name.
142 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
143 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800144 thread_data_t* t = new thread_data_t;
145 t->priority = threadPriority;
146 t->threadName = threadName ? strdup(threadName) : NULL;
147 t->entryFunction = entryFunction;
148 t->userData = userData;
149 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800150 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800151 }
152#endif
153
154 if (threadStackSize) {
155 pthread_attr_setstacksize(&attr, threadStackSize);
156 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800157
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800158 errno = 0;
159 pthread_t thread;
160 int result = pthread_create(&thread, &attr,
161 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700162 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800163 if (result != 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700164 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800165 "(android threadPriority=%d)",
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700166 entryFunction, result, strerror(errno), threadPriority);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800167 return 0;
168 }
169
Glenn Kastena538e262011-06-02 08:59:28 -0700170 // Note that *threadID is directly available to the parent only, as it is
171 // assigned after the child starts. Use memory barrier / lock if the child
172 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800173 if (threadId != NULL) {
174 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
175 }
176 return 1;
177}
178
Glenn Kastend731f072011-07-11 15:59:22 -0700179#ifdef HAVE_ANDROID_OS
180static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
181{
182 return (pthread_t) thread;
183}
184#endif
185
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800186android_thread_id_t androidGetThreadId()
187{
188 return (android_thread_id_t)pthread_self();
189}
190
191// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800192#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800193// ----------------------------------------------------------------------------
194
195/*
196 * Trampoline to make us __stdcall-compliant.
197 *
198 * We're expected to delete "vDetails" when we're done.
199 */
200struct threadDetails {
201 int (*func)(void*);
202 void* arg;
203};
204static __stdcall unsigned int threadIntermediary(void* vDetails)
205{
206 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
207 int result;
208
209 result = (*(pDetails->func))(pDetails->arg);
210
211 delete pDetails;
212
Steve Block8b4cf772011-10-12 17:27:03 +0100213 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800214 return (unsigned int) result;
215}
216
217/*
218 * Create and run a new thread.
219 */
220static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
221{
222 HANDLE hThread;
223 struct threadDetails* pDetails = new threadDetails; // must be on heap
224 unsigned int thrdaddr;
225
226 pDetails->func = fn;
227 pDetails->arg = arg;
228
229#if defined(HAVE__BEGINTHREADEX)
230 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
231 &thrdaddr);
232 if (hThread == 0)
233#elif defined(HAVE_CREATETHREAD)
234 hThread = CreateThread(NULL, 0,
235 (LPTHREAD_START_ROUTINE) threadIntermediary,
236 (void*) pDetails, 0, (DWORD*) &thrdaddr);
237 if (hThread == NULL)
238#endif
239 {
Steve Block8b4cf772011-10-12 17:27:03 +0100240 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800241 return false;
242 }
243
244#if defined(HAVE_CREATETHREAD)
245 /* close the management handle */
246 CloseHandle(hThread);
247#endif
248
249 if (id != NULL) {
250 *id = (android_thread_id_t)thrdaddr;
251 }
252
253 return true;
254}
255
256int androidCreateRawThreadEtc(android_thread_func_t fn,
257 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700258 const char* /*threadName*/,
259 int32_t /*threadPriority*/,
260 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800261 android_thread_id_t *threadId)
262{
263 return doCreateThread( fn, userData, threadId);
264}
265
266android_thread_id_t androidGetThreadId()
267{
268 return (android_thread_id_t)GetCurrentThreadId();
269}
270
271// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800272#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800273
274// ----------------------------------------------------------------------------
275
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800276int androidCreateThread(android_thread_func_t fn, void* arg)
277{
278 return createThreadEtc(fn, arg);
279}
280
281int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
282{
283 return createThreadEtc(fn, arg, "android:unnamed_thread",
284 PRIORITY_DEFAULT, 0, id);
285}
286
287static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
288
289int androidCreateThreadEtc(android_thread_func_t entryFunction,
290 void *userData,
291 const char* threadName,
292 int32_t threadPriority,
293 size_t threadStackSize,
294 android_thread_id_t *threadId)
295{
296 return gCreateThreadFn(entryFunction, userData, threadName,
297 threadPriority, threadStackSize, threadId);
298}
299
300void androidSetCreateThreadFunc(android_create_thread_fn func)
301{
302 gCreateThreadFn = func;
303}
304
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700305#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800306int androidSetThreadPriority(pid_t tid, int pri)
307{
308 int rc = 0;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800309
310#if !defined(_WIN32)
Dianne Hackborn235af972009-12-07 17:59:37 -0800311 int lasterr = 0;
312
Glenn Kastenfe34e452012-04-30 16:03:30 -0700313 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
314 rc = set_sched_policy(tid, SP_BACKGROUND);
315 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
316 rc = set_sched_policy(tid, SP_FOREGROUND);
Dianne Hackborn235af972009-12-07 17:59:37 -0800317 }
318
319 if (rc) {
320 lasterr = errno;
321 }
322
323 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
324 rc = INVALID_OPERATION;
325 } else {
326 errno = lasterr;
327 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800328#endif
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800329
Dianne Hackborn235af972009-12-07 17:59:37 -0800330 return rc;
331}
332
Andreas Huber8ddbed92011-09-15 12:21:40 -0700333int androidGetThreadPriority(pid_t tid) {
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800334#if !defined(_WIN32)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700335 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700336#else
337 return ANDROID_PRIORITY_NORMAL;
338#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700339}
340
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700341#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700342
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800343namespace android {
344
345/*
346 * ===========================================================================
347 * Mutex class
348 * ===========================================================================
349 */
350
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800351#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700352// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800353#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800354
355Mutex::Mutex()
356{
357 HANDLE hMutex;
358
359 assert(sizeof(hMutex) == sizeof(mState));
360
361 hMutex = CreateMutex(NULL, FALSE, NULL);
362 mState = (void*) hMutex;
363}
364
365Mutex::Mutex(const char* name)
366{
367 // XXX: name not used for now
368 HANDLE hMutex;
369
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200370 assert(sizeof(hMutex) == sizeof(mState));
371
372 hMutex = CreateMutex(NULL, FALSE, NULL);
373 mState = (void*) hMutex;
374}
375
376Mutex::Mutex(int type, const char* name)
377{
378 // XXX: type and name not used for now
379 HANDLE hMutex;
380
381 assert(sizeof(hMutex) == sizeof(mState));
382
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800383 hMutex = CreateMutex(NULL, FALSE, NULL);
384 mState = (void*) hMutex;
385}
386
387Mutex::~Mutex()
388{
389 CloseHandle((HANDLE) mState);
390}
391
392status_t Mutex::lock()
393{
394 DWORD dwWaitResult;
395 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
396 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
397}
398
399void Mutex::unlock()
400{
401 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100402 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800403}
404
405status_t Mutex::tryLock()
406{
407 DWORD dwWaitResult;
408
409 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
410 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100411 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800412 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
413}
414
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800415#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800416
417
418/*
419 * ===========================================================================
420 * Condition class
421 * ===========================================================================
422 */
423
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800424#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700425// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800426#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800427
428/*
429 * Windows doesn't have a condition variable solution. It's possible
430 * to create one, but it's easy to get it wrong. For a discussion, and
431 * the origin of this implementation, see:
432 *
433 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
434 *
435 * The implementation shown on the page does NOT follow POSIX semantics.
436 * As an optimization they require acquiring the external mutex before
437 * calling signal() and broadcast(), whereas POSIX only requires grabbing
438 * it before calling wait(). The implementation here has been un-optimized
439 * to have the correct behavior.
440 */
441typedef struct WinCondition {
442 // Number of waiting threads.
443 int waitersCount;
444
445 // Serialize access to waitersCount.
446 CRITICAL_SECTION waitersCountLock;
447
448 // Semaphore used to queue up threads waiting for the condition to
449 // become signaled.
450 HANDLE sema;
451
452 // An auto-reset event used by the broadcast/signal thread to wait
453 // for all the waiting thread(s) to wake up and be released from
454 // the semaphore.
455 HANDLE waitersDone;
456
457 // This mutex wouldn't be necessary if we required that the caller
458 // lock the external mutex before calling signal() and broadcast().
459 // I'm trying to mimic pthread semantics though.
460 HANDLE internalMutex;
461
462 // Keeps track of whether we were broadcasting or signaling. This
463 // allows us to optimize the code if we're just signaling.
464 bool wasBroadcast;
465
466 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
467 {
468 // Increment the wait count, avoiding race conditions.
469 EnterCriticalSection(&condState->waitersCountLock);
470 condState->waitersCount++;
471 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
472 // condState->waitersCount, getThreadId());
473 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800474
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800475 DWORD timeout = INFINITE;
476 if (abstime) {
477 nsecs_t reltime = *abstime - systemTime();
478 if (reltime < 0)
479 reltime = 0;
480 timeout = reltime/1000000;
481 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800482
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800483 // Atomically release the external mutex and wait on the semaphore.
484 DWORD res =
485 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800486
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800488
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800489 // Reacquire lock to avoid race conditions.
490 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800491
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800492 // No longer waiting.
493 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800494
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800495 // Check to see if we're the last waiter after a broadcast.
496 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800497
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800498 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
499 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800500
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800501 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800502
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800503 // If we're the last waiter thread during this particular broadcast
504 // then signal broadcast() that we're all awake. It'll drop the
505 // internal mutex.
506 if (lastWaiter) {
507 // Atomically signal the "waitersDone" event and wait until we
508 // can acquire the internal mutex. We want to do this in one step
509 // because it ensures that everybody is in the mutex FIFO before
510 // any thread has a chance to run. Without it, another thread
511 // could wake up, do work, and hop back in ahead of us.
512 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
513 INFINITE, FALSE);
514 } else {
515 // Grab the internal mutex.
516 WaitForSingleObject(condState->internalMutex, INFINITE);
517 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800518
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800519 // Release the internal and grab the external.
520 ReleaseMutex(condState->internalMutex);
521 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800522
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800523 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
524 }
525} WinCondition;
526
527/*
528 * Constructor. Set up the WinCondition stuff.
529 */
530Condition::Condition()
531{
532 WinCondition* condState = new WinCondition;
533
534 condState->waitersCount = 0;
535 condState->wasBroadcast = false;
536 // semaphore: no security, initial value of 0
537 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
538 InitializeCriticalSection(&condState->waitersCountLock);
539 // auto-reset event, not signaled initially
540 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
541 // used so we don't have to lock external mutex on signal/broadcast
542 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
543
544 mState = condState;
545}
546
547/*
548 * Destructor. Free Windows resources as well as our allocated storage.
549 */
550Condition::~Condition()
551{
552 WinCondition* condState = (WinCondition*) mState;
553 if (condState != NULL) {
554 CloseHandle(condState->sema);
555 CloseHandle(condState->waitersDone);
556 delete condState;
557 }
558}
559
560
561status_t Condition::wait(Mutex& mutex)
562{
563 WinCondition* condState = (WinCondition*) mState;
564 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800565
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800566 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
567}
568
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800569status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
570{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200571 WinCondition* condState = (WinCondition*) mState;
572 HANDLE hMutex = (HANDLE) mutex.mState;
573 nsecs_t absTime = systemTime()+reltime;
574
575 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800576}
577
578/*
579 * Signal the condition variable, allowing one thread to continue.
580 */
581void Condition::signal()
582{
583 WinCondition* condState = (WinCondition*) mState;
584
585 // Lock the internal mutex. This ensures that we don't clash with
586 // broadcast().
587 WaitForSingleObject(condState->internalMutex, INFINITE);
588
589 EnterCriticalSection(&condState->waitersCountLock);
590 bool haveWaiters = (condState->waitersCount > 0);
591 LeaveCriticalSection(&condState->waitersCountLock);
592
593 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
594 // down a notch.
595 if (haveWaiters)
596 ReleaseSemaphore(condState->sema, 1, 0);
597
598 // Release internal mutex.
599 ReleaseMutex(condState->internalMutex);
600}
601
602/*
603 * Signal the condition variable, allowing all threads to continue.
604 *
605 * First we have to wake up all threads waiting on the semaphore, then
606 * we wait until all of the threads have actually been woken before
607 * releasing the internal mutex. This ensures that all threads are woken.
608 */
609void Condition::broadcast()
610{
611 WinCondition* condState = (WinCondition*) mState;
612
613 // Lock the internal mutex. This keeps the guys we're waking up
614 // from getting too far.
615 WaitForSingleObject(condState->internalMutex, INFINITE);
616
617 EnterCriticalSection(&condState->waitersCountLock);
618 bool haveWaiters = false;
619
620 if (condState->waitersCount > 0) {
621 haveWaiters = true;
622 condState->wasBroadcast = true;
623 }
624
625 if (haveWaiters) {
626 // Wake up all the waiters.
627 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
628
629 LeaveCriticalSection(&condState->waitersCountLock);
630
631 // Wait for all awakened threads to acquire the counting semaphore.
632 // The last guy who was waiting sets this.
633 WaitForSingleObject(condState->waitersDone, INFINITE);
634
635 // Reset wasBroadcast. (No crit section needed because nobody
636 // else can wake up to poke at it.)
637 condState->wasBroadcast = 0;
638 } else {
639 // nothing to do
640 LeaveCriticalSection(&condState->waitersCountLock);
641 }
642
643 // Release internal mutex.
644 ReleaseMutex(condState->internalMutex);
645}
646
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800647#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800648
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800649// ----------------------------------------------------------------------------
650
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800651/*
652 * This is our thread object!
653 */
654
655Thread::Thread(bool canCallJava)
656 : mCanCallJava(canCallJava),
657 mThread(thread_id_t(-1)),
658 mLock("Thread::mLock"),
659 mStatus(NO_ERROR),
660 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800661#ifdef HAVE_ANDROID_OS
662 , mTid(-1)
663#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800664{
665}
666
667Thread::~Thread()
668{
669}
670
671status_t Thread::readyToRun()
672{
673 return NO_ERROR;
674}
675
676status_t Thread::run(const char* name, int32_t priority, size_t stack)
677{
678 Mutex::Autolock _l(mLock);
679
680 if (mRunning) {
681 // thread already started
682 return INVALID_OPERATION;
683 }
684
685 // reset status and exitPending to their default value, so we can
686 // try again after an error happened (either below, or in readyToRun())
687 mStatus = NO_ERROR;
688 mExitPending = false;
689 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800690
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800691 // hold a strong reference on ourself
692 mHoldSelf = this;
693
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800694 mRunning = true;
695
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800696 bool res;
697 if (mCanCallJava) {
698 res = createThreadEtc(_threadLoop,
699 this, name, priority, stack, &mThread);
700 } else {
701 res = androidCreateRawThreadEtc(_threadLoop,
702 this, name, priority, stack, &mThread);
703 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800704
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800705 if (res == false) {
706 mStatus = UNKNOWN_ERROR; // something happened!
707 mRunning = false;
708 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800709 mHoldSelf.clear(); // "this" may have gone away after this.
710
711 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800712 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800713
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800714 // Do not refer to mStatus here: The thread is already running (may, in fact
715 // already have exited with a valid mStatus result). The NO_ERROR indication
716 // here merely indicates successfully starting the thread and does not
717 // imply successful termination/execution.
718 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800719
720 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800721}
722
723int Thread::_threadLoop(void* user)
724{
725 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800726
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800727 sp<Thread> strong(self->mHoldSelf);
728 wp<Thread> weak(strong);
729 self->mHoldSelf.clear();
730
Kenny Rootdafff0b2011-02-16 10:13:53 -0800731#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700732 // this is very useful for debugging with gdb
733 self->mTid = gettid();
734#endif
735
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800736 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800737
738 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800739 bool result;
740 if (first) {
741 first = false;
742 self->mStatus = self->readyToRun();
743 result = (self->mStatus == NO_ERROR);
744
Glenn Kasten966a48f2011-02-01 11:32:29 -0800745 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800746 // Binder threads (and maybe others) rely on threadLoop
747 // running at least once after a successful ::readyToRun()
748 // (unless, of course, the thread has already been asked to exit
749 // at that point).
750 // This is because threads are essentially used like this:
751 // (new ThreadSubclass())->run();
752 // The caller therefore does not retain a strong reference to
753 // the thread and the thread would simply disappear after the
754 // successful ::readyToRun() call instead of entering the
755 // threadLoop at least once.
756 result = self->threadLoop();
757 }
758 } else {
759 result = self->threadLoop();
760 }
761
Glenn Kasten966a48f2011-02-01 11:32:29 -0800762 // establish a scope for mLock
763 {
764 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800765 if (result == false || self->mExitPending) {
766 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800767 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800768 // clear thread ID so that requestExitAndWait() does not exit if
769 // called by a new thread using the same thread ID as this one.
770 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800771 // note that interested observers blocked in requestExitAndWait are
772 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700773 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800774 break;
775 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800776 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800777
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800778 // Release our strong reference, to let a chance to the thread
779 // to die a peaceful death.
780 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700781 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800782 strong = weak.promote();
783 } while(strong != 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800784
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800785 return 0;
786}
787
788void Thread::requestExit()
789{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800790 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800791 mExitPending = true;
792}
793
794status_t Thread::requestExitAndWait()
795{
Glenn Kastena538e262011-06-02 08:59:28 -0700796 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800797 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000798 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800799 "Thread (this=%p): don't call waitForExit() from this "
800 "Thread object's thread. It's a guaranteed deadlock!",
801 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800802
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800803 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800804 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800805
Glenn Kastena538e262011-06-02 08:59:28 -0700806 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800807
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800808 while (mRunning == true) {
809 mThreadExitedCondition.wait(mLock);
810 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800811 // This next line is probably not needed any more, but is being left for
812 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800813 mExitPending = false;
814
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800815 return mStatus;
816}
817
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700818status_t Thread::join()
819{
820 Mutex::Autolock _l(mLock);
821 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000822 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700823 "Thread (this=%p): don't call join() from this "
824 "Thread object's thread. It's a guaranteed deadlock!",
825 this);
826
827 return WOULD_BLOCK;
828 }
829
830 while (mRunning == true) {
831 mThreadExitedCondition.wait(mLock);
832 }
833
834 return mStatus;
835}
836
Romain Guy31ba37f2013-03-11 14:34:56 -0700837bool Thread::isRunning() const {
838 Mutex::Autolock _l(mLock);
839 return mRunning;
840}
841
Glenn Kastend731f072011-07-11 15:59:22 -0700842#ifdef HAVE_ANDROID_OS
843pid_t Thread::getTid() const
844{
845 // mTid is not defined until the child initializes it, and the caller may need it earlier
846 Mutex::Autolock _l(mLock);
847 pid_t tid;
848 if (mRunning) {
849 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700850 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700851 } else {
852 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
853 tid = -1;
854 }
855 return tid;
856}
857#endif
858
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800859bool Thread::exitPending() const
860{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800861 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800862 return mExitPending;
863}
864
865
866
867}; // namespace android