blob: 1e014c64e0c52b83bbb883587ccbb3912b765b4f [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>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025#include <unistd.h>
26
Yabin Cui4a6e5a32015-01-26 19:48:54 -080027#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080028# include <pthread.h>
29# include <sched.h>
30# include <sys/resource.h>
Yabin Cui4a6e5a32015-01-26 19:48:54 -080031#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080032# include <windows.h>
33# include <stdint.h>
34# include <process.h>
35# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
36#endif
37
Elliott Hughes292ccd32014-12-15 12:52:53 -080038#if defined(__linux__)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080039#include <sys/prctl.h>
40#endif
41
Mark Salyzyn5bed8032014-04-30 11:10:46 -070042#include <utils/threads.h>
43#include <utils/Log.h>
44
45#include <cutils/sched_policy.h>
46
47#ifdef HAVE_ANDROID_OS
48# define __android_unused
49#else
50# define __android_unused __attribute__((__unused__))
51#endif
52
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080053/*
54 * ===========================================================================
55 * Thread wrappers
56 * ===========================================================================
57 */
58
59using namespace android;
60
61// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -080062#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080063// ----------------------------------------------------------------------------
64
65/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070066 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080067 *
68 * We create it "detached", so it cleans up after itself.
69 */
70
71typedef void* (*android_pthread_entry)(void*);
72
73struct thread_data_t {
74 thread_func_t entryFunction;
75 void* userData;
76 int priority;
77 char * threadName;
78
79 // we use this trampoline when we need to set the priority with
Glenn Kastend731f072011-07-11 15:59:22 -070080 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080081 static int trampoline(const thread_data_t* t) {
82 thread_func_t f = t->entryFunction;
83 void* u = t->userData;
84 int prio = t->priority;
85 char * name = t->threadName;
86 delete t;
87 setpriority(PRIO_PROCESS, 0, prio);
Glenn Kastenfe34e452012-04-30 16:03:30 -070088 if (prio >= ANDROID_PRIORITY_BACKGROUND) {
89 set_sched_policy(0, SP_BACKGROUND);
90 } else {
91 set_sched_policy(0, SP_FOREGROUND);
Dianne Hackborna78bab02010-09-09 15:50:18 -070092 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -080093
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080094 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080095 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080096 free(name);
97 }
98 return f(u);
99 }
100};
101
Mathias Agopian6090df82013-03-07 15:34:28 -0800102void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -0800103#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -0800104 // Mac OS doesn't have this, and we build libutil for the host too
105 int hasAt = 0;
106 int hasDot = 0;
107 const char *s = name;
108 while (*s) {
109 if (*s == '.') hasDot = 1;
110 else if (*s == '@') hasAt = 1;
111 s++;
112 }
113 int len = s - name;
114 if (len < 15 || hasAt || !hasDot) {
115 s = name;
116 } else {
117 s = name + len - 15;
118 }
119 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
120#endif
121}
122
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800123int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
124 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700125 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800126 int32_t threadPriority,
127 size_t threadStackSize,
128 android_thread_id_t *threadId)
129{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800130 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800131 pthread_attr_init(&attr);
132 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
133
134#ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */
135 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700136 // Now that the pthread_t has a method to find the associated
137 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
138 // this trampoline in some cases as the parent could set the properties
139 // for the child. However, there would be a race condition because the
140 // child becomes ready immediately, and it doesn't work for the name.
141 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
142 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800143 thread_data_t* t = new thread_data_t;
144 t->priority = threadPriority;
145 t->threadName = threadName ? strdup(threadName) : NULL;
146 t->entryFunction = entryFunction;
147 t->userData = userData;
148 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800149 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800150 }
151#endif
152
153 if (threadStackSize) {
154 pthread_attr_setstacksize(&attr, threadStackSize);
155 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800156
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800157 errno = 0;
158 pthread_t thread;
159 int result = pthread_create(&thread, &attr,
160 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700161 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800162 if (result != 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000163 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800164 "(android threadPriority=%d)",
165 entryFunction, result, errno, threadPriority);
166 return 0;
167 }
168
Glenn Kastena538e262011-06-02 08:59:28 -0700169 // Note that *threadID is directly available to the parent only, as it is
170 // assigned after the child starts. Use memory barrier / lock if the child
171 // or other threads also need access.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800172 if (threadId != NULL) {
173 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
174 }
175 return 1;
176}
177
Glenn Kastend731f072011-07-11 15:59:22 -0700178#ifdef HAVE_ANDROID_OS
179static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
180{
181 return (pthread_t) thread;
182}
183#endif
184
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800185android_thread_id_t androidGetThreadId()
186{
187 return (android_thread_id_t)pthread_self();
188}
189
190// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800191#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800192// ----------------------------------------------------------------------------
193
194/*
195 * Trampoline to make us __stdcall-compliant.
196 *
197 * We're expected to delete "vDetails" when we're done.
198 */
199struct threadDetails {
200 int (*func)(void*);
201 void* arg;
202};
203static __stdcall unsigned int threadIntermediary(void* vDetails)
204{
205 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
206 int result;
207
208 result = (*(pDetails->func))(pDetails->arg);
209
210 delete pDetails;
211
Steve Block8b4cf772011-10-12 17:27:03 +0100212 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800213 return (unsigned int) result;
214}
215
216/*
217 * Create and run a new thread.
218 */
219static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
220{
221 HANDLE hThread;
222 struct threadDetails* pDetails = new threadDetails; // must be on heap
223 unsigned int thrdaddr;
224
225 pDetails->func = fn;
226 pDetails->arg = arg;
227
228#if defined(HAVE__BEGINTHREADEX)
229 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
230 &thrdaddr);
231 if (hThread == 0)
232#elif defined(HAVE_CREATETHREAD)
233 hThread = CreateThread(NULL, 0,
234 (LPTHREAD_START_ROUTINE) threadIntermediary,
235 (void*) pDetails, 0, (DWORD*) &thrdaddr);
236 if (hThread == NULL)
237#endif
238 {
Steve Block8b4cf772011-10-12 17:27:03 +0100239 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800240 return false;
241 }
242
243#if defined(HAVE_CREATETHREAD)
244 /* close the management handle */
245 CloseHandle(hThread);
246#endif
247
248 if (id != NULL) {
249 *id = (android_thread_id_t)thrdaddr;
250 }
251
252 return true;
253}
254
255int androidCreateRawThreadEtc(android_thread_func_t fn,
256 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700257 const char* /*threadName*/,
258 int32_t /*threadPriority*/,
259 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800260 android_thread_id_t *threadId)
261{
262 return doCreateThread( fn, userData, threadId);
263}
264
265android_thread_id_t androidGetThreadId()
266{
267 return (android_thread_id_t)GetCurrentThreadId();
268}
269
270// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800271#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800272
273// ----------------------------------------------------------------------------
274
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800275int androidCreateThread(android_thread_func_t fn, void* arg)
276{
277 return createThreadEtc(fn, arg);
278}
279
280int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
281{
282 return createThreadEtc(fn, arg, "android:unnamed_thread",
283 PRIORITY_DEFAULT, 0, id);
284}
285
286static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
287
288int androidCreateThreadEtc(android_thread_func_t entryFunction,
289 void *userData,
290 const char* threadName,
291 int32_t threadPriority,
292 size_t threadStackSize,
293 android_thread_id_t *threadId)
294{
295 return gCreateThreadFn(entryFunction, userData, threadName,
296 threadPriority, threadStackSize, threadId);
297}
298
299void androidSetCreateThreadFunc(android_create_thread_fn func)
300{
301 gCreateThreadFn = func;
302}
303
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700304#ifdef HAVE_ANDROID_OS
Dianne Hackborn235af972009-12-07 17:59:37 -0800305int androidSetThreadPriority(pid_t tid, int pri)
306{
307 int rc = 0;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800308
309#if !defined(_WIN32)
Dianne Hackborn235af972009-12-07 17:59:37 -0800310 int lasterr = 0;
311
Glenn Kastenfe34e452012-04-30 16:03:30 -0700312 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
313 rc = set_sched_policy(tid, SP_BACKGROUND);
314 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
315 rc = set_sched_policy(tid, SP_FOREGROUND);
Dianne Hackborn235af972009-12-07 17:59:37 -0800316 }
317
318 if (rc) {
319 lasterr = errno;
320 }
321
322 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
323 rc = INVALID_OPERATION;
324 } else {
325 errno = lasterr;
326 }
Dianne Hackborn3432efa2009-12-08 16:38:01 -0800327#endif
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800328
Dianne Hackborn235af972009-12-07 17:59:37 -0800329 return rc;
330}
331
Andreas Huber8ddbed92011-09-15 12:21:40 -0700332int androidGetThreadPriority(pid_t tid) {
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800333#if !defined(_WIN32)
Andreas Huber8ddbed92011-09-15 12:21:40 -0700334 return getpriority(PRIO_PROCESS, tid);
Andreas Huber7b4ce612011-09-16 11:47:13 -0700335#else
336 return ANDROID_PRIORITY_NORMAL;
337#endif
Andreas Huber8ddbed92011-09-15 12:21:40 -0700338}
339
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700340#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700341
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800342namespace android {
343
344/*
345 * ===========================================================================
346 * Mutex class
347 * ===========================================================================
348 */
349
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800350#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700351// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800352#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800353
354Mutex::Mutex()
355{
356 HANDLE hMutex;
357
358 assert(sizeof(hMutex) == sizeof(mState));
359
360 hMutex = CreateMutex(NULL, FALSE, NULL);
361 mState = (void*) hMutex;
362}
363
364Mutex::Mutex(const char* name)
365{
366 // XXX: name not used for now
367 HANDLE hMutex;
368
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200369 assert(sizeof(hMutex) == sizeof(mState));
370
371 hMutex = CreateMutex(NULL, FALSE, NULL);
372 mState = (void*) hMutex;
373}
374
375Mutex::Mutex(int type, const char* name)
376{
377 // XXX: type and name not used for now
378 HANDLE hMutex;
379
380 assert(sizeof(hMutex) == sizeof(mState));
381
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800382 hMutex = CreateMutex(NULL, FALSE, NULL);
383 mState = (void*) hMutex;
384}
385
386Mutex::~Mutex()
387{
388 CloseHandle((HANDLE) mState);
389}
390
391status_t Mutex::lock()
392{
393 DWORD dwWaitResult;
394 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
395 return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
396}
397
398void Mutex::unlock()
399{
400 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100401 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800402}
403
404status_t Mutex::tryLock()
405{
406 DWORD dwWaitResult;
407
408 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
409 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100410 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800411 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
412}
413
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800414#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800415
416
417/*
418 * ===========================================================================
419 * Condition class
420 * ===========================================================================
421 */
422
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800423#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700424// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800425#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800426
427/*
428 * Windows doesn't have a condition variable solution. It's possible
429 * to create one, but it's easy to get it wrong. For a discussion, and
430 * the origin of this implementation, see:
431 *
432 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
433 *
434 * The implementation shown on the page does NOT follow POSIX semantics.
435 * As an optimization they require acquiring the external mutex before
436 * calling signal() and broadcast(), whereas POSIX only requires grabbing
437 * it before calling wait(). The implementation here has been un-optimized
438 * to have the correct behavior.
439 */
440typedef struct WinCondition {
441 // Number of waiting threads.
442 int waitersCount;
443
444 // Serialize access to waitersCount.
445 CRITICAL_SECTION waitersCountLock;
446
447 // Semaphore used to queue up threads waiting for the condition to
448 // become signaled.
449 HANDLE sema;
450
451 // An auto-reset event used by the broadcast/signal thread to wait
452 // for all the waiting thread(s) to wake up and be released from
453 // the semaphore.
454 HANDLE waitersDone;
455
456 // This mutex wouldn't be necessary if we required that the caller
457 // lock the external mutex before calling signal() and broadcast().
458 // I'm trying to mimic pthread semantics though.
459 HANDLE internalMutex;
460
461 // Keeps track of whether we were broadcasting or signaling. This
462 // allows us to optimize the code if we're just signaling.
463 bool wasBroadcast;
464
465 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
466 {
467 // Increment the wait count, avoiding race conditions.
468 EnterCriticalSection(&condState->waitersCountLock);
469 condState->waitersCount++;
470 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
471 // condState->waitersCount, getThreadId());
472 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800473
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800474 DWORD timeout = INFINITE;
475 if (abstime) {
476 nsecs_t reltime = *abstime - systemTime();
477 if (reltime < 0)
478 reltime = 0;
479 timeout = reltime/1000000;
480 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800481
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800482 // Atomically release the external mutex and wait on the semaphore.
483 DWORD res =
484 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800487
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800488 // Reacquire lock to avoid race conditions.
489 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800490
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800491 // No longer waiting.
492 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800493
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800494 // Check to see if we're the last waiter after a broadcast.
495 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800496
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800497 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
498 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800499
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800500 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800501
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800502 // If we're the last waiter thread during this particular broadcast
503 // then signal broadcast() that we're all awake. It'll drop the
504 // internal mutex.
505 if (lastWaiter) {
506 // Atomically signal the "waitersDone" event and wait until we
507 // can acquire the internal mutex. We want to do this in one step
508 // because it ensures that everybody is in the mutex FIFO before
509 // any thread has a chance to run. Without it, another thread
510 // could wake up, do work, and hop back in ahead of us.
511 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
512 INFINITE, FALSE);
513 } else {
514 // Grab the internal mutex.
515 WaitForSingleObject(condState->internalMutex, INFINITE);
516 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800517
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800518 // Release the internal and grab the external.
519 ReleaseMutex(condState->internalMutex);
520 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800521
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800522 return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
523 }
524} WinCondition;
525
526/*
527 * Constructor. Set up the WinCondition stuff.
528 */
529Condition::Condition()
530{
531 WinCondition* condState = new WinCondition;
532
533 condState->waitersCount = 0;
534 condState->wasBroadcast = false;
535 // semaphore: no security, initial value of 0
536 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
537 InitializeCriticalSection(&condState->waitersCountLock);
538 // auto-reset event, not signaled initially
539 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
540 // used so we don't have to lock external mutex on signal/broadcast
541 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
542
543 mState = condState;
544}
545
546/*
547 * Destructor. Free Windows resources as well as our allocated storage.
548 */
549Condition::~Condition()
550{
551 WinCondition* condState = (WinCondition*) mState;
552 if (condState != NULL) {
553 CloseHandle(condState->sema);
554 CloseHandle(condState->waitersDone);
555 delete condState;
556 }
557}
558
559
560status_t Condition::wait(Mutex& mutex)
561{
562 WinCondition* condState = (WinCondition*) mState;
563 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800564
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800565 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
566}
567
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800568status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
569{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200570 WinCondition* condState = (WinCondition*) mState;
571 HANDLE hMutex = (HANDLE) mutex.mState;
572 nsecs_t absTime = systemTime()+reltime;
573
574 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800575}
576
577/*
578 * Signal the condition variable, allowing one thread to continue.
579 */
580void Condition::signal()
581{
582 WinCondition* condState = (WinCondition*) mState;
583
584 // Lock the internal mutex. This ensures that we don't clash with
585 // broadcast().
586 WaitForSingleObject(condState->internalMutex, INFINITE);
587
588 EnterCriticalSection(&condState->waitersCountLock);
589 bool haveWaiters = (condState->waitersCount > 0);
590 LeaveCriticalSection(&condState->waitersCountLock);
591
592 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
593 // down a notch.
594 if (haveWaiters)
595 ReleaseSemaphore(condState->sema, 1, 0);
596
597 // Release internal mutex.
598 ReleaseMutex(condState->internalMutex);
599}
600
601/*
602 * Signal the condition variable, allowing all threads to continue.
603 *
604 * First we have to wake up all threads waiting on the semaphore, then
605 * we wait until all of the threads have actually been woken before
606 * releasing the internal mutex. This ensures that all threads are woken.
607 */
608void Condition::broadcast()
609{
610 WinCondition* condState = (WinCondition*) mState;
611
612 // Lock the internal mutex. This keeps the guys we're waking up
613 // from getting too far.
614 WaitForSingleObject(condState->internalMutex, INFINITE);
615
616 EnterCriticalSection(&condState->waitersCountLock);
617 bool haveWaiters = false;
618
619 if (condState->waitersCount > 0) {
620 haveWaiters = true;
621 condState->wasBroadcast = true;
622 }
623
624 if (haveWaiters) {
625 // Wake up all the waiters.
626 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
627
628 LeaveCriticalSection(&condState->waitersCountLock);
629
630 // Wait for all awakened threads to acquire the counting semaphore.
631 // The last guy who was waiting sets this.
632 WaitForSingleObject(condState->waitersDone, INFINITE);
633
634 // Reset wasBroadcast. (No crit section needed because nobody
635 // else can wake up to poke at it.)
636 condState->wasBroadcast = 0;
637 } else {
638 // nothing to do
639 LeaveCriticalSection(&condState->waitersCountLock);
640 }
641
642 // Release internal mutex.
643 ReleaseMutex(condState->internalMutex);
644}
645
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800646#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800647
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800648// ----------------------------------------------------------------------------
649
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800650/*
651 * This is our thread object!
652 */
653
654Thread::Thread(bool canCallJava)
655 : mCanCallJava(canCallJava),
656 mThread(thread_id_t(-1)),
657 mLock("Thread::mLock"),
658 mStatus(NO_ERROR),
659 mExitPending(false), mRunning(false)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800660#ifdef HAVE_ANDROID_OS
661 , mTid(-1)
662#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800663{
664}
665
666Thread::~Thread()
667{
668}
669
670status_t Thread::readyToRun()
671{
672 return NO_ERROR;
673}
674
675status_t Thread::run(const char* name, int32_t priority, size_t stack)
676{
677 Mutex::Autolock _l(mLock);
678
679 if (mRunning) {
680 // thread already started
681 return INVALID_OPERATION;
682 }
683
684 // reset status and exitPending to their default value, so we can
685 // try again after an error happened (either below, or in readyToRun())
686 mStatus = NO_ERROR;
687 mExitPending = false;
688 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800689
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800690 // hold a strong reference on ourself
691 mHoldSelf = this;
692
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800693 mRunning = true;
694
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800695 bool res;
696 if (mCanCallJava) {
697 res = createThreadEtc(_threadLoop,
698 this, name, priority, stack, &mThread);
699 } else {
700 res = androidCreateRawThreadEtc(_threadLoop,
701 this, name, priority, stack, &mThread);
702 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800703
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800704 if (res == false) {
705 mStatus = UNKNOWN_ERROR; // something happened!
706 mRunning = false;
707 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800708 mHoldSelf.clear(); // "this" may have gone away after this.
709
710 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800711 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800712
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800713 // Do not refer to mStatus here: The thread is already running (may, in fact
714 // already have exited with a valid mStatus result). The NO_ERROR indication
715 // here merely indicates successfully starting the thread and does not
716 // imply successful termination/execution.
717 return NO_ERROR;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800718
719 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800720}
721
722int Thread::_threadLoop(void* user)
723{
724 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800725
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800726 sp<Thread> strong(self->mHoldSelf);
727 wp<Thread> weak(strong);
728 self->mHoldSelf.clear();
729
Kenny Rootdafff0b2011-02-16 10:13:53 -0800730#ifdef HAVE_ANDROID_OS
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700731 // this is very useful for debugging with gdb
732 self->mTid = gettid();
733#endif
734
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800735 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800736
737 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800738 bool result;
739 if (first) {
740 first = false;
741 self->mStatus = self->readyToRun();
742 result = (self->mStatus == NO_ERROR);
743
Glenn Kasten966a48f2011-02-01 11:32:29 -0800744 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800745 // Binder threads (and maybe others) rely on threadLoop
746 // running at least once after a successful ::readyToRun()
747 // (unless, of course, the thread has already been asked to exit
748 // at that point).
749 // This is because threads are essentially used like this:
750 // (new ThreadSubclass())->run();
751 // The caller therefore does not retain a strong reference to
752 // the thread and the thread would simply disappear after the
753 // successful ::readyToRun() call instead of entering the
754 // threadLoop at least once.
755 result = self->threadLoop();
756 }
757 } else {
758 result = self->threadLoop();
759 }
760
Glenn Kasten966a48f2011-02-01 11:32:29 -0800761 // establish a scope for mLock
762 {
763 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800764 if (result == false || self->mExitPending) {
765 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800766 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800767 // clear thread ID so that requestExitAndWait() does not exit if
768 // called by a new thread using the same thread ID as this one.
769 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800770 // note that interested observers blocked in requestExitAndWait are
771 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700772 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800773 break;
774 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800775 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800776
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800777 // Release our strong reference, to let a chance to the thread
778 // to die a peaceful death.
779 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700780 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800781 strong = weak.promote();
782 } while(strong != 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800783
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800784 return 0;
785}
786
787void Thread::requestExit()
788{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800789 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800790 mExitPending = true;
791}
792
793status_t Thread::requestExitAndWait()
794{
Glenn Kastena538e262011-06-02 08:59:28 -0700795 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800796 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000797 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800798 "Thread (this=%p): don't call waitForExit() from this "
799 "Thread object's thread. It's a guaranteed deadlock!",
800 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800801
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800802 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800803 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800804
Glenn Kastena538e262011-06-02 08:59:28 -0700805 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800806
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800807 while (mRunning == true) {
808 mThreadExitedCondition.wait(mLock);
809 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800810 // This next line is probably not needed any more, but is being left for
811 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800812 mExitPending = false;
813
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800814 return mStatus;
815}
816
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700817status_t Thread::join()
818{
819 Mutex::Autolock _l(mLock);
820 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000821 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700822 "Thread (this=%p): don't call join() from this "
823 "Thread object's thread. It's a guaranteed deadlock!",
824 this);
825
826 return WOULD_BLOCK;
827 }
828
829 while (mRunning == true) {
830 mThreadExitedCondition.wait(mLock);
831 }
832
833 return mStatus;
834}
835
Romain Guy31ba37f2013-03-11 14:34:56 -0700836bool Thread::isRunning() const {
837 Mutex::Autolock _l(mLock);
838 return mRunning;
839}
840
Glenn Kastend731f072011-07-11 15:59:22 -0700841#ifdef HAVE_ANDROID_OS
842pid_t Thread::getTid() const
843{
844 // mTid is not defined until the child initializes it, and the caller may need it earlier
845 Mutex::Autolock _l(mLock);
846 pid_t tid;
847 if (mRunning) {
848 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700849 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700850 } else {
851 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
852 tid = -1;
853 }
854 return tid;
855}
856#endif
857
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800858bool Thread::exitPending() const
859{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800860 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800861 return mExitPending;
862}
863
864
865
866}; // namespace android