blob: 111d46af9e2d93225d8ba5c47bc21d34bfc52a11 [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
Aditya Kumarbe2cc9f2024-09-05 14:03:59 -070063typedef int (*android_pthread_entry)(void*);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080064
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
Aditya Kumarbe2cc9f2024-09-05 14:03:59 -070091// Adapted from bionic's implmenetation of trampoline to make C11 thrd_create
92// work with pthread_create.
93struct libutil_thread_data {
94 android_pthread_entry _Nonnull entry_func;
95 void* _Nullable entry_func_arg;
96};
97
98static void* _Nonnull libutil_thread_trampoline(void* _Nonnull arg) {
99 libutil_thread_data *data_ptr = static_cast<libutil_thread_data*>(arg);
100 int result = data_ptr->entry_func(data_ptr->entry_func_arg);
101 delete data_ptr;
102 return reinterpret_cast<void*>(static_cast<uintptr_t>(result));
103}
104
Mathias Agopian6090df82013-03-07 15:34:28 -0800105void androidSetThreadName(const char* name) {
Elliott Hughes292ccd32014-12-15 12:52:53 -0800106#if defined(__linux__)
Mathias Agopian6090df82013-03-07 15:34:28 -0800107 // Mac OS doesn't have this, and we build libutil for the host too
108 int hasAt = 0;
109 int hasDot = 0;
110 const char *s = name;
111 while (*s) {
112 if (*s == '.') hasDot = 1;
113 else if (*s == '@') hasAt = 1;
114 s++;
115 }
116 int len = s - name;
117 if (len < 15 || hasAt || !hasDot) {
118 s = name;
119 } else {
120 s = name + len - 15;
121 }
122 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
123#endif
124}
125
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800126int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
127 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700128 const char* threadName __android_unused,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800129 int32_t threadPriority,
130 size_t threadStackSize,
131 android_thread_id_t *threadId)
132{
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800133 pthread_attr_t attr;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800134 pthread_attr_init(&attr);
135 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
136
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700137#if defined(__ANDROID__) /* valgrind is rejecting RT-priority create reqs */
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800138 if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
Glenn Kastend731f072011-07-11 15:59:22 -0700139 // Now that the pthread_t has a method to find the associated
140 // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
141 // this trampoline in some cases as the parent could set the properties
142 // for the child. However, there would be a race condition because the
143 // child becomes ready immediately, and it doesn't work for the name.
144 // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
145 // proposed but not yet accepted.
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800146 thread_data_t* t = new thread_data_t;
147 t->priority = threadPriority;
148 t->threadName = threadName ? strdup(threadName) : NULL;
149 t->entryFunction = entryFunction;
150 t->userData = userData;
151 entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800152 userData = t;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800153 }
154#endif
155
156 if (threadStackSize) {
157 pthread_attr_setstacksize(&attr, threadStackSize);
158 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800159
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800160 errno = 0;
161 pthread_t thread;
Aditya Kumarbe2cc9f2024-09-05 14:03:59 -0700162
163 libutil_thread_data* pthread_arg = new libutil_thread_data;
164 pthread_arg->entry_func = entryFunction;
165 pthread_arg->entry_func_arg = userData;
166
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800167 int result = pthread_create(&thread, &attr,
Aditya Kumarbe2cc9f2024-09-05 14:03:59 -0700168 libutil_thread_trampoline, pthread_arg);
Le-Chun Wud8734d12011-07-14 14:27:18 -0700169 pthread_attr_destroy(&attr);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800170 if (result != 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700171 ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, %s)\n"
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800172 "(android threadPriority=%d)",
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700173 entryFunction, result, strerror(errno), threadPriority);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800174 return 0;
175 }
176
Glenn Kastena538e262011-06-02 08:59:28 -0700177 // Note that *threadID is directly available to the parent only, as it is
178 // assigned after the child starts. Use memory barrier / lock if the child
179 // or other threads also need access.
Yi Konge1731a42018-07-16 18:11:34 -0700180 if (threadId != nullptr) {
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800181 *threadId = (android_thread_id_t)thread; // XXX: this is not portable
182 }
183 return 1;
184}
185
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700186#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700187static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
188{
189 return (pthread_t) thread;
190}
191#endif
192
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800193android_thread_id_t androidGetThreadId()
194{
195 return (android_thread_id_t)pthread_self();
196}
197
198// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800199#else // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800200// ----------------------------------------------------------------------------
201
202/*
203 * Trampoline to make us __stdcall-compliant.
204 *
205 * We're expected to delete "vDetails" when we're done.
206 */
207struct threadDetails {
208 int (*func)(void*);
209 void* arg;
210};
211static __stdcall unsigned int threadIntermediary(void* vDetails)
212{
213 struct threadDetails* pDetails = (struct threadDetails*) vDetails;
214 int result;
215
216 result = (*(pDetails->func))(pDetails->arg);
217
218 delete pDetails;
219
Steve Block8b4cf772011-10-12 17:27:03 +0100220 ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800221 return (unsigned int) result;
222}
223
224/*
225 * Create and run a new thread.
226 */
227static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
228{
229 HANDLE hThread;
230 struct threadDetails* pDetails = new threadDetails; // must be on heap
231 unsigned int thrdaddr;
232
233 pDetails->func = fn;
234 pDetails->arg = arg;
235
236#if defined(HAVE__BEGINTHREADEX)
237 hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
238 &thrdaddr);
239 if (hThread == 0)
240#elif defined(HAVE_CREATETHREAD)
241 hThread = CreateThread(NULL, 0,
242 (LPTHREAD_START_ROUTINE) threadIntermediary,
243 (void*) pDetails, 0, (DWORD*) &thrdaddr);
244 if (hThread == NULL)
245#endif
246 {
Steve Block8b4cf772011-10-12 17:27:03 +0100247 ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800248 return false;
249 }
250
251#if defined(HAVE_CREATETHREAD)
252 /* close the management handle */
253 CloseHandle(hThread);
254#endif
255
256 if (id != NULL) {
257 *id = (android_thread_id_t)thrdaddr;
258 }
259
260 return true;
261}
262
263int androidCreateRawThreadEtc(android_thread_func_t fn,
264 void *userData,
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700265 const char* /*threadName*/,
266 int32_t /*threadPriority*/,
267 size_t /*threadStackSize*/,
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800268 android_thread_id_t *threadId)
269{
270 return doCreateThread( fn, userData, threadId);
271}
272
273android_thread_id_t androidGetThreadId()
274{
275 return (android_thread_id_t)GetCurrentThreadId();
276}
277
278// ----------------------------------------------------------------------------
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800279#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800280
281// ----------------------------------------------------------------------------
282
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800283int androidCreateThread(android_thread_func_t fn, void* arg)
284{
285 return createThreadEtc(fn, arg);
286}
287
288int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
289{
290 return createThreadEtc(fn, arg, "android:unnamed_thread",
291 PRIORITY_DEFAULT, 0, id);
292}
293
294static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;
295
296int androidCreateThreadEtc(android_thread_func_t entryFunction,
297 void *userData,
298 const char* threadName,
299 int32_t threadPriority,
300 size_t threadStackSize,
301 android_thread_id_t *threadId)
302{
303 return gCreateThreadFn(entryFunction, userData, threadName,
304 threadPriority, threadStackSize, threadId);
305}
306
307void androidSetCreateThreadFunc(android_create_thread_fn func)
308{
309 gCreateThreadFn = func;
310}
311
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700312#if defined(__ANDROID__)
Rick Yiufa02bb92020-09-27 11:21:11 +0800313int androidSetThreadPriority(pid_t tid, int pri)
314{
Dianne Hackborn235af972009-12-07 17:59:37 -0800315 int rc = 0;
Dianne Hackborn235af972009-12-07 17:59:37 -0800316
Dianne Hackborn235af972009-12-07 17:59:37 -0800317 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
318 rc = INVALID_OPERATION;
319 } else {
Greg Kaiser044be6b2022-02-08 07:37:13 -0800320 errno = 0;
Dianne Hackborn235af972009-12-07 17:59:37 -0800321 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800322
Dianne Hackborn235af972009-12-07 17:59:37 -0800323 return rc;
324}
325
Andreas Huber8ddbed92011-09-15 12:21:40 -0700326int androidGetThreadPriority(pid_t tid) {
327 return getpriority(PRIO_PROCESS, tid);
328}
329
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700330#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700331
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800332namespace android {
333
334/*
335 * ===========================================================================
336 * Mutex class
337 * ===========================================================================
338 */
339
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800340#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700341// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800342#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800343
344Mutex::Mutex()
345{
346 HANDLE hMutex;
347
348 assert(sizeof(hMutex) == sizeof(mState));
349
350 hMutex = CreateMutex(NULL, FALSE, NULL);
351 mState = (void*) hMutex;
352}
353
Dan Willemsen528f1442017-11-29 18:06:11 -0800354Mutex::Mutex(const char* /*name*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800355{
356 // XXX: name not used for now
357 HANDLE hMutex;
358
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200359 assert(sizeof(hMutex) == sizeof(mState));
360
361 hMutex = CreateMutex(NULL, FALSE, NULL);
362 mState = (void*) hMutex;
363}
364
Dan Willemsen528f1442017-11-29 18:06:11 -0800365Mutex::Mutex(int /*type*/, const char* /*name*/)
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200366{
367 // XXX: type and name not used for now
368 HANDLE hMutex;
369
370 assert(sizeof(hMutex) == sizeof(mState));
371
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800372 hMutex = CreateMutex(NULL, FALSE, NULL);
373 mState = (void*) hMutex;
374}
375
376Mutex::~Mutex()
377{
378 CloseHandle((HANDLE) mState);
379}
380
381status_t Mutex::lock()
382{
383 DWORD dwWaitResult;
384 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
Elliott Hughes643268f2018-10-08 11:10:11 -0700385 return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800386}
387
388void Mutex::unlock()
389{
390 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100391 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800392}
393
394status_t Mutex::tryLock()
395{
396 DWORD dwWaitResult;
397
398 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
399 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100400 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800401 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
402}
403
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800404#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800405
406
407/*
408 * ===========================================================================
409 * Condition class
410 * ===========================================================================
411 */
412
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800413#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700414// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800415#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800416
417/*
418 * Windows doesn't have a condition variable solution. It's possible
419 * to create one, but it's easy to get it wrong. For a discussion, and
420 * the origin of this implementation, see:
421 *
422 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
423 *
424 * The implementation shown on the page does NOT follow POSIX semantics.
425 * As an optimization they require acquiring the external mutex before
426 * calling signal() and broadcast(), whereas POSIX only requires grabbing
427 * it before calling wait(). The implementation here has been un-optimized
428 * to have the correct behavior.
429 */
430typedef struct WinCondition {
431 // Number of waiting threads.
432 int waitersCount;
433
434 // Serialize access to waitersCount.
435 CRITICAL_SECTION waitersCountLock;
436
437 // Semaphore used to queue up threads waiting for the condition to
438 // become signaled.
439 HANDLE sema;
440
441 // An auto-reset event used by the broadcast/signal thread to wait
442 // for all the waiting thread(s) to wake up and be released from
443 // the semaphore.
444 HANDLE waitersDone;
445
446 // This mutex wouldn't be necessary if we required that the caller
447 // lock the external mutex before calling signal() and broadcast().
448 // I'm trying to mimic pthread semantics though.
449 HANDLE internalMutex;
450
451 // Keeps track of whether we were broadcasting or signaling. This
452 // allows us to optimize the code if we're just signaling.
453 bool wasBroadcast;
454
455 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
456 {
457 // Increment the wait count, avoiding race conditions.
458 EnterCriticalSection(&condState->waitersCountLock);
459 condState->waitersCount++;
460 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
461 // condState->waitersCount, getThreadId());
462 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800463
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800464 DWORD timeout = INFINITE;
465 if (abstime) {
466 nsecs_t reltime = *abstime - systemTime();
467 if (reltime < 0)
468 reltime = 0;
469 timeout = reltime/1000000;
470 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800471
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800472 // Atomically release the external mutex and wait on the semaphore.
473 DWORD res =
474 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800475
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800476 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800477
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800478 // Reacquire lock to avoid race conditions.
479 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800480
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800481 // No longer waiting.
482 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800483
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800484 // Check to see if we're the last waiter after a broadcast.
485 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800486
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800487 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
488 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800489
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800490 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800491
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800492 // If we're the last waiter thread during this particular broadcast
493 // then signal broadcast() that we're all awake. It'll drop the
494 // internal mutex.
495 if (lastWaiter) {
496 // Atomically signal the "waitersDone" event and wait until we
497 // can acquire the internal mutex. We want to do this in one step
498 // because it ensures that everybody is in the mutex FIFO before
499 // any thread has a chance to run. Without it, another thread
500 // could wake up, do work, and hop back in ahead of us.
501 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
502 INFINITE, FALSE);
503 } else {
504 // Grab the internal mutex.
505 WaitForSingleObject(condState->internalMutex, INFINITE);
506 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800507
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800508 // Release the internal and grab the external.
509 ReleaseMutex(condState->internalMutex);
510 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800511
Elliott Hughes643268f2018-10-08 11:10:11 -0700512 return res == WAIT_OBJECT_0 ? OK : -1;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800513 }
514} WinCondition;
515
516/*
517 * Constructor. Set up the WinCondition stuff.
518 */
519Condition::Condition()
520{
521 WinCondition* condState = new WinCondition;
522
523 condState->waitersCount = 0;
524 condState->wasBroadcast = false;
525 // semaphore: no security, initial value of 0
526 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
527 InitializeCriticalSection(&condState->waitersCountLock);
528 // auto-reset event, not signaled initially
529 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
530 // used so we don't have to lock external mutex on signal/broadcast
531 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
532
533 mState = condState;
534}
535
536/*
537 * Destructor. Free Windows resources as well as our allocated storage.
538 */
539Condition::~Condition()
540{
541 WinCondition* condState = (WinCondition*) mState;
542 if (condState != NULL) {
543 CloseHandle(condState->sema);
544 CloseHandle(condState->waitersDone);
545 delete condState;
546 }
547}
548
549
550status_t Condition::wait(Mutex& mutex)
551{
552 WinCondition* condState = (WinCondition*) mState;
553 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800554
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800555 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
556}
557
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800558status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
559{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200560 WinCondition* condState = (WinCondition*) mState;
561 HANDLE hMutex = (HANDLE) mutex.mState;
562 nsecs_t absTime = systemTime()+reltime;
563
564 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800565}
566
567/*
568 * Signal the condition variable, allowing one thread to continue.
569 */
570void Condition::signal()
571{
572 WinCondition* condState = (WinCondition*) mState;
573
574 // Lock the internal mutex. This ensures that we don't clash with
575 // broadcast().
576 WaitForSingleObject(condState->internalMutex, INFINITE);
577
578 EnterCriticalSection(&condState->waitersCountLock);
579 bool haveWaiters = (condState->waitersCount > 0);
580 LeaveCriticalSection(&condState->waitersCountLock);
581
582 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
583 // down a notch.
584 if (haveWaiters)
585 ReleaseSemaphore(condState->sema, 1, 0);
586
587 // Release internal mutex.
588 ReleaseMutex(condState->internalMutex);
589}
590
591/*
592 * Signal the condition variable, allowing all threads to continue.
593 *
594 * First we have to wake up all threads waiting on the semaphore, then
595 * we wait until all of the threads have actually been woken before
596 * releasing the internal mutex. This ensures that all threads are woken.
597 */
598void Condition::broadcast()
599{
600 WinCondition* condState = (WinCondition*) mState;
601
602 // Lock the internal mutex. This keeps the guys we're waking up
603 // from getting too far.
604 WaitForSingleObject(condState->internalMutex, INFINITE);
605
606 EnterCriticalSection(&condState->waitersCountLock);
607 bool haveWaiters = false;
608
609 if (condState->waitersCount > 0) {
610 haveWaiters = true;
611 condState->wasBroadcast = true;
612 }
613
614 if (haveWaiters) {
615 // Wake up all the waiters.
616 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
617
618 LeaveCriticalSection(&condState->waitersCountLock);
619
620 // Wait for all awakened threads to acquire the counting semaphore.
621 // The last guy who was waiting sets this.
622 WaitForSingleObject(condState->waitersDone, INFINITE);
623
624 // Reset wasBroadcast. (No crit section needed because nobody
625 // else can wake up to poke at it.)
626 condState->wasBroadcast = 0;
627 } else {
628 // nothing to do
629 LeaveCriticalSection(&condState->waitersCountLock);
630 }
631
632 // Release internal mutex.
633 ReleaseMutex(condState->internalMutex);
634}
635
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800636#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800637
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800638// ----------------------------------------------------------------------------
639
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800640/*
641 * This is our thread object!
642 */
643
644Thread::Thread(bool canCallJava)
Elliott Hughes643268f2018-10-08 11:10:11 -0700645 : mCanCallJava(canCallJava),
646 mThread(thread_id_t(-1)),
647 mLock("Thread::mLock"),
648 mStatus(OK),
649 mExitPending(false),
650 mRunning(false)
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700651#if defined(__ANDROID__)
Elliott Hughes643268f2018-10-08 11:10:11 -0700652 ,
653 mTid(-1)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800654#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800655{
656}
657
658Thread::~Thread()
659{
660}
661
662status_t Thread::readyToRun()
663{
Elliott Hughes643268f2018-10-08 11:10:11 -0700664 return OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800665}
666
667status_t Thread::run(const char* name, int32_t priority, size_t stack)
668{
Brian Carlstrome71b9142016-03-12 16:08:12 -0800669 LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
670
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800671 Mutex::Autolock _l(mLock);
672
673 if (mRunning) {
674 // thread already started
675 return INVALID_OPERATION;
676 }
677
678 // reset status and exitPending to their default value, so we can
679 // try again after an error happened (either below, or in readyToRun())
Elliott Hughes643268f2018-10-08 11:10:11 -0700680 mStatus = OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800681 mExitPending = false;
682 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800683
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800684 // hold a strong reference on ourself
Steven Morelanda06e68c2021-04-27 00:09:23 +0000685 mHoldSelf = sp<Thread>::fromExisting(this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800686
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800687 mRunning = true;
688
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800689 bool res;
690 if (mCanCallJava) {
691 res = createThreadEtc(_threadLoop,
692 this, name, priority, stack, &mThread);
693 } else {
694 res = androidCreateRawThreadEtc(_threadLoop,
695 this, name, priority, stack, &mThread);
696 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800697
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800698 if (res == false) {
699 mStatus = UNKNOWN_ERROR; // something happened!
700 mRunning = false;
701 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800702 mHoldSelf.clear(); // "this" may have gone away after this.
703
704 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800705 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800706
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800707 // Do not refer to mStatus here: The thread is already running (may, in fact
Elliott Hughes643268f2018-10-08 11:10:11 -0700708 // already have exited with a valid mStatus result). The OK indication
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800709 // here merely indicates successfully starting the thread and does not
710 // imply successful termination/execution.
Elliott Hughes643268f2018-10-08 11:10:11 -0700711 return OK;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800712
713 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800714}
715
716int Thread::_threadLoop(void* user)
717{
718 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800719
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800720 sp<Thread> strong(self->mHoldSelf);
721 wp<Thread> weak(strong);
722 self->mHoldSelf.clear();
723
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700724#if defined(__ANDROID__)
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700725 // this is very useful for debugging with gdb
726 self->mTid = gettid();
727#endif
728
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800729 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800730
731 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800732 bool result;
733 if (first) {
734 first = false;
735 self->mStatus = self->readyToRun();
Elliott Hughes643268f2018-10-08 11:10:11 -0700736 result = (self->mStatus == OK);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800737
Glenn Kasten966a48f2011-02-01 11:32:29 -0800738 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800739 // Binder threads (and maybe others) rely on threadLoop
740 // running at least once after a successful ::readyToRun()
741 // (unless, of course, the thread has already been asked to exit
742 // at that point).
743 // This is because threads are essentially used like this:
744 // (new ThreadSubclass())->run();
745 // The caller therefore does not retain a strong reference to
746 // the thread and the thread would simply disappear after the
747 // successful ::readyToRun() call instead of entering the
748 // threadLoop at least once.
749 result = self->threadLoop();
750 }
751 } else {
752 result = self->threadLoop();
753 }
754
Glenn Kasten966a48f2011-02-01 11:32:29 -0800755 // establish a scope for mLock
756 {
757 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800758 if (result == false || self->mExitPending) {
759 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800760 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800761 // clear thread ID so that requestExitAndWait() does not exit if
762 // called by a new thread using the same thread ID as this one.
763 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800764 // note that interested observers blocked in requestExitAndWait are
765 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700766 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800767 break;
768 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800769 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800770
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800771 // Release our strong reference, to let a chance to the thread
772 // to die a peaceful death.
773 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700774 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800775 strong = weak.promote();
Yi Konge1731a42018-07-16 18:11:34 -0700776 } while(strong != nullptr);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800777
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800778 return 0;
779}
780
781void Thread::requestExit()
782{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800783 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800784 mExitPending = true;
785}
786
787status_t Thread::requestExitAndWait()
788{
Glenn Kastena538e262011-06-02 08:59:28 -0700789 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800790 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000791 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800792 "Thread (this=%p): don't call waitForExit() from this "
793 "Thread object's thread. It's a guaranteed deadlock!",
794 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800795
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800796 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800797 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800798
Glenn Kastena538e262011-06-02 08:59:28 -0700799 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800800
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800801 while (mRunning == true) {
802 mThreadExitedCondition.wait(mLock);
803 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800804 // This next line is probably not needed any more, but is being left for
805 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800806 mExitPending = false;
807
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800808 return mStatus;
809}
810
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700811status_t Thread::join()
812{
813 Mutex::Autolock _l(mLock);
814 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000815 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700816 "Thread (this=%p): don't call join() from this "
817 "Thread object's thread. It's a guaranteed deadlock!",
818 this);
819
820 return WOULD_BLOCK;
821 }
822
823 while (mRunning == true) {
824 mThreadExitedCondition.wait(mLock);
825 }
826
827 return mStatus;
828}
829
Romain Guy31ba37f2013-03-11 14:34:56 -0700830bool Thread::isRunning() const {
831 Mutex::Autolock _l(mLock);
832 return mRunning;
833}
834
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700835#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700836pid_t Thread::getTid() const
837{
838 // mTid is not defined until the child initializes it, and the caller may need it earlier
839 Mutex::Autolock _l(mLock);
840 pid_t tid;
841 if (mRunning) {
842 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700843 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700844 } else {
845 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
846 tid = -1;
847 }
848 return tid;
849}
850#endif
851
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800852bool Thread::exitPending() const
853{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800854 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800855 return mExitPending;
856}
857
858
859
860}; // namespace android