blob: 0b96ab0bbcb8876212754a679c36f1753674a737 [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>
Mathias Agopian22dbf392017-02-28 15:06:51 -080021#include <utils/AndroidThreads.h>
Rick Yiuf7f44422019-12-26 19:35:03 +080022#include <utils/Thread.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080023
Yabin Cui4a6e5a32015-01-26 19:48:54 -080024#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080025# include <sys/resource.h>
Yabin Cui4a6e5a32015-01-26 19:48:54 -080026#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080027# include <windows.h>
28# include <stdint.h>
29# include <process.h>
30# define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
31#endif
32
Elliott Hughes292ccd32014-12-15 12:52:53 -080033#if defined(__linux__)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080034#include <sys/prctl.h>
35#endif
36
Steven Moreland066e6252023-10-07 00:29:44 +000037#include <log/log.h>
Mark Salyzyn5bed8032014-04-30 11:10:46 -070038
Rick Yiuf7f44422019-12-26 19:35:03 +080039#if defined(__ANDROID__)
Mark Salyzyn5bed8032014-04-30 11:10:46 -070040# define __android_unused
41#else
42# define __android_unused __attribute__((__unused__))
43#endif
44
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080045/*
46 * ===========================================================================
47 * Thread wrappers
48 * ===========================================================================
49 */
50
51using namespace android;
52
53// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -080054#if !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080055// ----------------------------------------------------------------------------
56
57/*
Dianne Hackborn16d217e2010-09-03 17:07:07 -070058 * Create and run a new thread.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080059 *
60 * We create it "detached", so it cleans up after itself.
61 */
62
63typedef void* (*android_pthread_entry)(void*);
64
Rick Yiuf7f44422019-12-26 19:35:03 +080065#if defined(__ANDROID__)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080066struct thread_data_t {
67 thread_func_t entryFunction;
68 void* userData;
69 int priority;
70 char * threadName;
71
72 // we use this trampoline when we need to set the priority with
Glenn Kastend731f072011-07-11 15:59:22 -070073 // nice/setpriority, and name with prctl.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080074 static int trampoline(const thread_data_t* t) {
75 thread_func_t f = t->entryFunction;
76 void* u = t->userData;
77 int prio = t->priority;
78 char * name = t->threadName;
79 delete t;
80 setpriority(PRIO_PROCESS, 0, prio);
Rick Yiuf7f44422019-12-26 19:35:03 +080081
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080082 if (name) {
Mathias Agopian6090df82013-03-07 15:34:28 -080083 androidSetThreadName(name);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080084 free(name);
85 }
86 return f(u);
87 }
88};
Rick Yiuf7f44422019-12-26 19:35:03 +080089#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080090
Mathias Agopian6090df82013-03-07 15:34:28 -080091void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -080092#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -080093 // Mac OS doesn't have this, and we build libutil for the host too
94 int hasAt = 0;
95 int hasDot = 0;
96 const char *s = name;
97 while (*s) {
98 if (*s == '.') hasDot = 1;
99 else if (*s == '@') hasAt = 1;
100 s++;
101 }
102 int len = s - name;
103 if (len < 15 || hasAt || !hasDot) {
104 s = name;
105 } else {
106 s = name + len - 15;
107 }
108 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
109#endif
110}
111
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800112int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
113 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700114 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800115 int32_t threadPriority,
116 size_t threadStackSize,
117 android_thread_id_t *threadId)
118{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800119 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800120 pthread_attr_init(&attr);
121 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
122
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700123#if defined(__ANDROID__) /* valgrind is rejecting RT-priority create reqs */
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800124 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700125 // Now that the pthread_t has a method to find the associated
126 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
127 // this trampoline in some cases as the parent could set the properties
128 // for the child. However, there would be a race condition because the
129 // child becomes ready immediately, and it doesn't work for the name.
130 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
131 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800132 thread_data_t* t = new thread_data_t;
133 t->priority = threadPriority;
134 t->threadName = threadName ? strdup(threadName) : NULL;
135 t->entryFunction = entryFunction;
136 t->userData = userData;
137 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800138 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800139 }
140#endif
141
142 if (threadStackSize) {
143 pthread_attr_setstacksize(&attr, threadStackSize);
144 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800145
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800146 errno = 0;
147 pthread_t thread;
148 int result = pthread_create(&thread, &attr,
149 (android_pthread_entry)entryFunction, userData);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700150 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800151 if (result != 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700152 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800153 "(android threadPriority=%d)",
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700154 entryFunction, result, strerror(errno), threadPriority);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800155 return 0;
156 }
157
Glenn Kastena538e262011-06-02 08:59:28 -0700158 // Note that *threadID is directly available to the parent only, as it is
159 // assigned after the child starts. Use memory barrier / lock if the child
160 // or other threads also need access.
Yi Konge1731a42018-07-16 18:11:34 -0700161 if (threadId != nullptr) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800162 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
163 }
164 return 1;
165}
166
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700167#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700168static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
169{
170 return (pthread_t) thread;
171}
172#endif
173
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800174android_thread_id_t androidGetThreadId()
175{
176 return (android_thread_id_t)pthread_self();
177}
178
179// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800180#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800181// ----------------------------------------------------------------------------
182
183/*
184 * Trampoline to make us __stdcall-compliant.
185 *
186 * We're expected to delete "vDetails" when we're done.
187 */
188struct threadDetails {
189 int (*func)(void*);
190 void* arg;
191};
192static __stdcall unsigned int threadIntermediary(void* vDetails)
193{
194 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
195 int result;
196
197 result = (*(pDetails->func))(pDetails->arg);
198
199 delete pDetails;
200
Steve Block8b4cf772011-10-12 17:27:03 +0100201 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800202 return (unsigned int) result;
203}
204
205/*
206 * Create and run a new thread.
207 */
208static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
209{
210 HANDLE hThread;
211 struct threadDetails* pDetails = new threadDetails; // must be on heap
212 unsigned int thrdaddr;
213
214 pDetails->func = fn;
215 pDetails->arg = arg;
216
217#if defined(HAVE__BEGINTHREADEX)
218 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
219 &thrdaddr);
220 if (hThread == 0)
221#elif defined(HAVE_CREATETHREAD)
222 hThread = CreateThread(NULL, 0,
223 (LPTHREAD_START_ROUTINE) threadIntermediary,
224 (void*) pDetails, 0, (DWORD*) &thrdaddr);
225 if (hThread == NULL)
226#endif
227 {
Steve Block8b4cf772011-10-12 17:27:03 +0100228 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800229 return false;
230 }
231
232#if defined(HAVE_CREATETHREAD)
233 /* close the management handle */
234 CloseHandle(hThread);
235#endif
236
237 if (id != NULL) {
238 *id = (android_thread_id_t)thrdaddr;
239 }
240
241 return true;
242}
243
244int androidCreateRawThreadEtc(android_thread_func_t fn,
245 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700246 const char* /*threadName*/,
247 int32_t /*threadPriority*/,
248 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800249 android_thread_id_t *threadId)
250{
251 return doCreateThread( fn, userData, threadId);
252}
253
254android_thread_id_t androidGetThreadId()
255{
256 return (android_thread_id_t)GetCurrentThreadId();
257}
258
259// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800260#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800261
262// ----------------------------------------------------------------------------
263
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800264int androidCreateThread(android_thread_func_t fn, void* arg)
265{
266 return createThreadEtc(fn, arg);
267}
268
269int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
270{
271 return createThreadEtc(fn, arg, "android:unnamed_thread",
272 PRIORITY_DEFAULT, 0, id);
273}
274
275static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
276
277int androidCreateThreadEtc(android_thread_func_t entryFunction,
278 void *userData,
279 const char* threadName,
280 int32_t threadPriority,
281 size_t threadStackSize,
282 android_thread_id_t *threadId)
283{
284 return gCreateThreadFn(entryFunction, userData, threadName,
285 threadPriority, threadStackSize, threadId);
286}
287
288void androidSetCreateThreadFunc(android_create_thread_fn func)
289{
290 gCreateThreadFn = func;
291}
292
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700293#if defined(__ANDROID__)
Rick Yiufa02bb92020-09-27 11:21:11 +0800294int androidSetThreadPriority(pid_t tid, int pri)
295{
Dianne Hackborn235af972009-12-07 17:59:37 -0800296 int rc = 0;
Rick Yiuf7f44422019-12-26 19:35:03 +0800297 int curr_pri = getpriority(PRIO_PROCESS, tid);
298
299 if (curr_pri == pri) {
300 return rc;
301 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800302
Dianne Hackborn235af972009-12-07 17:59:37 -0800303 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
304 rc = INVALID_OPERATION;
305 } else {
Greg Kaiser044be6b2022-02-08 07:37:13 -0800306 errno = 0;
Dianne Hackborn235af972009-12-07 17:59:37 -0800307 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800308
Dianne Hackborn235af972009-12-07 17:59:37 -0800309 return rc;
310}
311
Andreas Huber8ddbed92011-09-15 12:21:40 -0700312int androidGetThreadPriority(pid_t tid) {
313 return getpriority(PRIO_PROCESS, tid);
314}
315
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700316#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700317
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800318namespace android {
319
320/*
321 * ===========================================================================
322 * Mutex class
323 * ===========================================================================
324 */
325
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800326#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700327// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800328#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800329
330Mutex::Mutex()
331{
332 HANDLE hMutex;
333
334 assert(sizeof(hMutex) == sizeof(mState));
335
336 hMutex = CreateMutex(NULL, FALSE, NULL);
337 mState = (void*) hMutex;
338}
339
Dan Willemsen528f1442017-11-29 18:06:11 -0800340Mutex::Mutex(const char* /*name*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800341{
342 // XXX: name not used for now
343 HANDLE hMutex;
344
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200345 assert(sizeof(hMutex) == sizeof(mState));
346
347 hMutex = CreateMutex(NULL, FALSE, NULL);
348 mState = (void*) hMutex;
349}
350
Dan Willemsen528f1442017-11-29 18:06:11 -0800351Mutex::Mutex(int /*type*/, const char* /*name*/)
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200352{
353 // XXX: type and name not used for now
354 HANDLE hMutex;
355
356 assert(sizeof(hMutex) == sizeof(mState));
357
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800358 hMutex = CreateMutex(NULL, FALSE, NULL);
359 mState = (void*) hMutex;
360}
361
362Mutex::~Mutex()
363{
364 CloseHandle((HANDLE) mState);
365}
366
367status_t Mutex::lock()
368{
369 DWORD dwWaitResult;
370 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
Elliott Hughes643268f2018-10-08 11:10:11 -0700371 return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800372}
373
374void Mutex::unlock()
375{
376 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100377 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800378}
379
380status_t Mutex::tryLock()
381{
382 DWORD dwWaitResult;
383
384 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
385 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100386 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800387 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
388}
389
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800390#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391
392
393/*
394 * ===========================================================================
395 * Condition class
396 * ===========================================================================
397 */
398
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800399#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700400// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800401#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800402
403/*
404 * Windows doesn't have a condition variable solution. It's possible
405 * to create one, but it's easy to get it wrong. For a discussion, and
406 * the origin of this implementation, see:
407 *
408 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
409 *
410 * The implementation shown on the page does NOT follow POSIX semantics.
411 * As an optimization they require acquiring the external mutex before
412 * calling signal() and broadcast(), whereas POSIX only requires grabbing
413 * it before calling wait(). The implementation here has been un-optimized
414 * to have the correct behavior.
415 */
416typedef struct WinCondition {
417 // Number of waiting threads.
418 int waitersCount;
419
420 // Serialize access to waitersCount.
421 CRITICAL_SECTION waitersCountLock;
422
423 // Semaphore used to queue up threads waiting for the condition to
424 // become signaled.
425 HANDLE sema;
426
427 // An auto-reset event used by the broadcast/signal thread to wait
428 // for all the waiting thread(s) to wake up and be released from
429 // the semaphore.
430 HANDLE waitersDone;
431
432 // This mutex wouldn't be necessary if we required that the caller
433 // lock the external mutex before calling signal() and broadcast().
434 // I'm trying to mimic pthread semantics though.
435 HANDLE internalMutex;
436
437 // Keeps track of whether we were broadcasting or signaling. This
438 // allows us to optimize the code if we're just signaling.
439 bool wasBroadcast;
440
441 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
442 {
443 // Increment the wait count, avoiding race conditions.
444 EnterCriticalSection(&condState->waitersCountLock);
445 condState->waitersCount++;
446 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
447 // condState->waitersCount, getThreadId());
448 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800449
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800450 DWORD timeout = INFINITE;
451 if (abstime) {
452 nsecs_t reltime = *abstime - systemTime();
453 if (reltime < 0)
454 reltime = 0;
455 timeout = reltime/1000000;
456 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800457
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800458 // Atomically release the external mutex and wait on the semaphore.
459 DWORD res =
460 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800461
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800462 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800463
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800464 // Reacquire lock to avoid race conditions.
465 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800466
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800467 // No longer waiting.
468 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800469
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800470 // Check to see if we're the last waiter after a broadcast.
471 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800472
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800473 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
474 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800475
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800476 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800477
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800478 // If we're the last waiter thread during this particular broadcast
479 // then signal broadcast() that we're all awake. It'll drop the
480 // internal mutex.
481 if (lastWaiter) {
482 // Atomically signal the "waitersDone" event and wait until we
483 // can acquire the internal mutex. We want to do this in one step
484 // because it ensures that everybody is in the mutex FIFO before
485 // any thread has a chance to run. Without it, another thread
486 // could wake up, do work, and hop back in ahead of us.
487 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
488 INFINITE, FALSE);
489 } else {
490 // Grab the internal mutex.
491 WaitForSingleObject(condState->internalMutex, INFINITE);
492 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800493
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800494 // Release the internal and grab the external.
495 ReleaseMutex(condState->internalMutex);
496 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800497
Elliott Hughes643268f2018-10-08 11:10:11 -0700498 return res == WAIT_OBJECT_0 ? OK : -1;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800499 }
500} WinCondition;
501
502/*
503 * Constructor. Set up the WinCondition stuff.
504 */
505Condition::Condition()
506{
507 WinCondition* condState = new WinCondition;
508
509 condState->waitersCount = 0;
510 condState->wasBroadcast = false;
511 // semaphore: no security, initial value of 0
512 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
513 InitializeCriticalSection(&condState->waitersCountLock);
514 // auto-reset event, not signaled initially
515 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
516 // used so we don't have to lock external mutex on signal/broadcast
517 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
518
519 mState = condState;
520}
521
522/*
523 * Destructor. Free Windows resources as well as our allocated storage.
524 */
525Condition::~Condition()
526{
527 WinCondition* condState = (WinCondition*) mState;
528 if (condState != NULL) {
529 CloseHandle(condState->sema);
530 CloseHandle(condState->waitersDone);
531 delete condState;
532 }
533}
534
535
536status_t Condition::wait(Mutex& mutex)
537{
538 WinCondition* condState = (WinCondition*) mState;
539 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800540
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800541 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
542}
543
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800544status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
545{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200546 WinCondition* condState = (WinCondition*) mState;
547 HANDLE hMutex = (HANDLE) mutex.mState;
548 nsecs_t absTime = systemTime()+reltime;
549
550 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800551}
552
553/*
554 * Signal the condition variable, allowing one thread to continue.
555 */
556void Condition::signal()
557{
558 WinCondition* condState = (WinCondition*) mState;
559
560 // Lock the internal mutex. This ensures that we don't clash with
561 // broadcast().
562 WaitForSingleObject(condState->internalMutex, INFINITE);
563
564 EnterCriticalSection(&condState->waitersCountLock);
565 bool haveWaiters = (condState->waitersCount > 0);
566 LeaveCriticalSection(&condState->waitersCountLock);
567
568 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
569 // down a notch.
570 if (haveWaiters)
571 ReleaseSemaphore(condState->sema, 1, 0);
572
573 // Release internal mutex.
574 ReleaseMutex(condState->internalMutex);
575}
576
577/*
578 * Signal the condition variable, allowing all threads to continue.
579 *
580 * First we have to wake up all threads waiting on the semaphore, then
581 * we wait until all of the threads have actually been woken before
582 * releasing the internal mutex. This ensures that all threads are woken.
583 */
584void Condition::broadcast()
585{
586 WinCondition* condState = (WinCondition*) mState;
587
588 // Lock the internal mutex. This keeps the guys we're waking up
589 // from getting too far.
590 WaitForSingleObject(condState->internalMutex, INFINITE);
591
592 EnterCriticalSection(&condState->waitersCountLock);
593 bool haveWaiters = false;
594
595 if (condState->waitersCount > 0) {
596 haveWaiters = true;
597 condState->wasBroadcast = true;
598 }
599
600 if (haveWaiters) {
601 // Wake up all the waiters.
602 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
603
604 LeaveCriticalSection(&condState->waitersCountLock);
605
606 // Wait for all awakened threads to acquire the counting semaphore.
607 // The last guy who was waiting sets this.
608 WaitForSingleObject(condState->waitersDone, INFINITE);
609
610 // Reset wasBroadcast. (No crit section needed because nobody
611 // else can wake up to poke at it.)
612 condState->wasBroadcast = 0;
613 } else {
614 // nothing to do
615 LeaveCriticalSection(&condState->waitersCountLock);
616 }
617
618 // Release internal mutex.
619 ReleaseMutex(condState->internalMutex);
620}
621
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800622#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800623
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800624// ----------------------------------------------------------------------------
625
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800626/*
627 * This is our thread object!
628 */
629
630Thread::Thread(bool canCallJava)
Elliott Hughes643268f2018-10-08 11:10:11 -0700631 : mCanCallJava(canCallJava),
632 mThread(thread_id_t(-1)),
633 mLock("Thread::mLock"),
634 mStatus(OK),
635 mExitPending(false),
636 mRunning(false)
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700637#if defined(__ANDROID__)
Elliott Hughes643268f2018-10-08 11:10:11 -0700638 ,
639 mTid(-1)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800640#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800641{
642}
643
644Thread::~Thread()
645{
646}
647
648status_t Thread::readyToRun()
649{
Elliott Hughes643268f2018-10-08 11:10:11 -0700650 return OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800651}
652
653status_t Thread::run(const char* name, int32_t priority, size_t stack)
654{
Brian Carlstrome71b9142016-03-12 16:08:12 -0800655 LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
656
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800657 Mutex::Autolock _l(mLock);
658
659 if (mRunning) {
660 // thread already started
661 return INVALID_OPERATION;
662 }
663
664 // reset status and exitPending to their default value, so we can
665 // try again after an error happened (either below, or in readyToRun())
Elliott Hughes643268f2018-10-08 11:10:11 -0700666 mStatus = OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800667 mExitPending = false;
668 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800669
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800670 // hold a strong reference on ourself
Steven Morelanda06e68c2021-04-27 00:09:23 +0000671 mHoldSelf = sp<Thread>::fromExisting(this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800672
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800673 mRunning = true;
674
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800675 bool res;
676 if (mCanCallJava) {
677 res = createThreadEtc(_threadLoop,
678 this, name, priority, stack, &mThread);
679 } else {
680 res = androidCreateRawThreadEtc(_threadLoop,
681 this, name, priority, stack, &mThread);
682 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800683
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800684 if (res == false) {
685 mStatus = UNKNOWN_ERROR; // something happened!
686 mRunning = false;
687 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800688 mHoldSelf.clear(); // "this" may have gone away after this.
689
690 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800691 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800692
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800693 // Do not refer to mStatus here: The thread is already running (may, in fact
Elliott Hughes643268f2018-10-08 11:10:11 -0700694 // already have exited with a valid mStatus result). The OK indication
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800695 // here merely indicates successfully starting the thread and does not
696 // imply successful termination/execution.
Elliott Hughes643268f2018-10-08 11:10:11 -0700697 return OK;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800698
699 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800700}
701
702int Thread::_threadLoop(void* user)
703{
704 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800705
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800706 sp<Thread> strong(self->mHoldSelf);
707 wp<Thread> weak(strong);
708 self->mHoldSelf.clear();
709
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700710#if defined(__ANDROID__)
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700711 // this is very useful for debugging with gdb
712 self->mTid = gettid();
713#endif
714
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800715 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800716
717 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800718 bool result;
719 if (first) {
720 first = false;
721 self->mStatus = self->readyToRun();
Elliott Hughes643268f2018-10-08 11:10:11 -0700722 result = (self->mStatus == OK);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800723
Glenn Kasten966a48f2011-02-01 11:32:29 -0800724 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800725 // Binder threads (and maybe others) rely on threadLoop
726 // running at least once after a successful ::readyToRun()
727 // (unless, of course, the thread has already been asked to exit
728 // at that point).
729 // This is because threads are essentially used like this:
730 // (new ThreadSubclass())->run();
731 // The caller therefore does not retain a strong reference to
732 // the thread and the thread would simply disappear after the
733 // successful ::readyToRun() call instead of entering the
734 // threadLoop at least once.
735 result = self->threadLoop();
736 }
737 } else {
738 result = self->threadLoop();
739 }
740
Glenn Kasten966a48f2011-02-01 11:32:29 -0800741 // establish a scope for mLock
742 {
743 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800744 if (result == false || self->mExitPending) {
745 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800746 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800747 // clear thread ID so that requestExitAndWait() does not exit if
748 // called by a new thread using the same thread ID as this one.
749 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800750 // note that interested observers blocked in requestExitAndWait are
751 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700752 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800753 break;
754 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800755 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800756
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800757 // Release our strong reference, to let a chance to the thread
758 // to die a peaceful death.
759 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700760 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800761 strong = weak.promote();
Yi Konge1731a42018-07-16 18:11:34 -0700762 } while(strong != nullptr);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800763
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800764 return 0;
765}
766
767void Thread::requestExit()
768{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800769 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800770 mExitPending = true;
771}
772
773status_t Thread::requestExitAndWait()
774{
Glenn Kastena538e262011-06-02 08:59:28 -0700775 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800776 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000777 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800778 "Thread (this=%p): don't call waitForExit() from this "
779 "Thread object's thread. It's a guaranteed deadlock!",
780 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800781
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800782 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800783 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800784
Glenn Kastena538e262011-06-02 08:59:28 -0700785 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800786
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800787 while (mRunning == true) {
788 mThreadExitedCondition.wait(mLock);
789 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800790 // This next line is probably not needed any more, but is being left for
791 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800792 mExitPending = false;
793
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800794 return mStatus;
795}
796
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700797status_t Thread::join()
798{
799 Mutex::Autolock _l(mLock);
800 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000801 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700802 "Thread (this=%p): don't call join() from this "
803 "Thread object's thread. It's a guaranteed deadlock!",
804 this);
805
806 return WOULD_BLOCK;
807 }
808
809 while (mRunning == true) {
810 mThreadExitedCondition.wait(mLock);
811 }
812
813 return mStatus;
814}
815
Romain Guy31ba37f2013-03-11 14:34:56 -0700816bool Thread::isRunning() const {
817 Mutex::Autolock _l(mLock);
818 return mRunning;
819}
820
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700821#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700822pid_t Thread::getTid() const
823{
824 // mTid is not defined until the child initializes it, and the caller may need it earlier
825 Mutex::Autolock _l(mLock);
826 pid_t tid;
827 if (mRunning) {
828 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700829 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700830 } else {
831 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
832 tid = -1;
833 }
834 return tid;
835}
836#endif
837
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800838bool Thread::exitPending() const
839{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800840 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800841 return mExitPending;
842}
843
844
845
846}; // namespace android