blob: d8d75acf47168de05389a8fd1e42b6cbb5f9a210 [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;
Rick Yiuf7f44422019-12-26 19:35:03 +0800316 int curr_pri = getpriority(PRIO_PROCESS, tid);
317
318 if (curr_pri == pri) {
319 return rc;
320 }
Dianne Hackborn235af972009-12-07 17:59:37 -0800321
Dianne Hackborn235af972009-12-07 17:59:37 -0800322 if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
323 rc = INVALID_OPERATION;
324 } else {
Greg Kaiser044be6b2022-02-08 07:37:13 -0800325 errno = 0;
Dianne Hackborn235af972009-12-07 17:59:37 -0800326 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800327
Dianne Hackborn235af972009-12-07 17:59:37 -0800328 return rc;
329}
330
Andreas Huber8ddbed92011-09-15 12:21:40 -0700331int androidGetThreadPriority(pid_t tid) {
332 return getpriority(PRIO_PROCESS, tid);
333}
334
Jeff Brown27e6eaa2012-03-16 22:18:39 -0700335#endif
Glenn Kasten6fbe0a82011-06-22 16:20:37 -0700336
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800337namespace android {
338
339/*
340 * ===========================================================================
341 * Mutex class
342 * ===========================================================================
343 */
344
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800345#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700346// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800347#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800348
349Mutex::Mutex()
350{
351 HANDLE hMutex;
352
353 assert(sizeof(hMutex) == sizeof(mState));
354
355 hMutex = CreateMutex(NULL, FALSE, NULL);
356 mState = (void*) hMutex;
357}
358
Dan Willemsen528f1442017-11-29 18:06:11 -0800359Mutex::Mutex(const char* /*name*/)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800360{
361 // XXX: name not used for now
362 HANDLE hMutex;
363
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200364 assert(sizeof(hMutex) == sizeof(mState));
365
366 hMutex = CreateMutex(NULL, FALSE, NULL);
367 mState = (void*) hMutex;
368}
369
Dan Willemsen528f1442017-11-29 18:06:11 -0800370Mutex::Mutex(int /*type*/, const char* /*name*/)
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200371{
372 // XXX: type and name not used for now
373 HANDLE hMutex;
374
375 assert(sizeof(hMutex) == sizeof(mState));
376
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800377 hMutex = CreateMutex(NULL, FALSE, NULL);
378 mState = (void*) hMutex;
379}
380
381Mutex::~Mutex()
382{
383 CloseHandle((HANDLE) mState);
384}
385
386status_t Mutex::lock()
387{
388 DWORD dwWaitResult;
389 dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
Elliott Hughes643268f2018-10-08 11:10:11 -0700390 return dwWaitResult != WAIT_OBJECT_0 ? -1 : OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800391}
392
393void Mutex::unlock()
394{
395 if (!ReleaseMutex((HANDLE) mState))
Steve Block8b4cf772011-10-12 17:27:03 +0100396 ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800397}
398
399status_t Mutex::tryLock()
400{
401 DWORD dwWaitResult;
402
403 dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
404 if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
Steve Block8b4cf772011-10-12 17:27:03 +0100405 ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800406 return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
407}
408
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800409#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800410
411
412/*
413 * ===========================================================================
414 * Condition class
415 * ===========================================================================
416 */
417
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800418#if !defined(_WIN32)
Mathias Agopian15554362009-07-12 23:11:20 -0700419// implemented as inlines in threads.h
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800420#else
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800421
422/*
423 * Windows doesn't have a condition variable solution. It's possible
424 * to create one, but it's easy to get it wrong. For a discussion, and
425 * the origin of this implementation, see:
426 *
427 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
428 *
429 * The implementation shown on the page does NOT follow POSIX semantics.
430 * As an optimization they require acquiring the external mutex before
431 * calling signal() and broadcast(), whereas POSIX only requires grabbing
432 * it before calling wait(). The implementation here has been un-optimized
433 * to have the correct behavior.
434 */
435typedef struct WinCondition {
436 // Number of waiting threads.
437 int waitersCount;
438
439 // Serialize access to waitersCount.
440 CRITICAL_SECTION waitersCountLock;
441
442 // Semaphore used to queue up threads waiting for the condition to
443 // become signaled.
444 HANDLE sema;
445
446 // An auto-reset event used by the broadcast/signal thread to wait
447 // for all the waiting thread(s) to wake up and be released from
448 // the semaphore.
449 HANDLE waitersDone;
450
451 // This mutex wouldn't be necessary if we required that the caller
452 // lock the external mutex before calling signal() and broadcast().
453 // I'm trying to mimic pthread semantics though.
454 HANDLE internalMutex;
455
456 // Keeps track of whether we were broadcasting or signaling. This
457 // allows us to optimize the code if we're just signaling.
458 bool wasBroadcast;
459
460 status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
461 {
462 // Increment the wait count, avoiding race conditions.
463 EnterCriticalSection(&condState->waitersCountLock);
464 condState->waitersCount++;
465 //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
466 // condState->waitersCount, getThreadId());
467 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800468
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800469 DWORD timeout = INFINITE;
470 if (abstime) {
471 nsecs_t reltime = *abstime - systemTime();
472 if (reltime < 0)
473 reltime = 0;
474 timeout = reltime/1000000;
475 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800476
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800477 // Atomically release the external mutex and wait on the semaphore.
478 DWORD res =
479 SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800480
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800481 //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800482
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800483 // Reacquire lock to avoid race conditions.
484 EnterCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800485
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800486 // No longer waiting.
487 condState->waitersCount--;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800488
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800489 // Check to see if we're the last waiter after a broadcast.
490 bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800491
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800492 //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
493 // lastWaiter, condState->wasBroadcast, condState->waitersCount);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800494
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800495 LeaveCriticalSection(&condState->waitersCountLock);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800496
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800497 // If we're the last waiter thread during this particular broadcast
498 // then signal broadcast() that we're all awake. It'll drop the
499 // internal mutex.
500 if (lastWaiter) {
501 // Atomically signal the "waitersDone" event and wait until we
502 // can acquire the internal mutex. We want to do this in one step
503 // because it ensures that everybody is in the mutex FIFO before
504 // any thread has a chance to run. Without it, another thread
505 // could wake up, do work, and hop back in ahead of us.
506 SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
507 INFINITE, FALSE);
508 } else {
509 // Grab the internal mutex.
510 WaitForSingleObject(condState->internalMutex, INFINITE);
511 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800512
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800513 // Release the internal and grab the external.
514 ReleaseMutex(condState->internalMutex);
515 WaitForSingleObject(hMutex, INFINITE);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800516
Elliott Hughes643268f2018-10-08 11:10:11 -0700517 return res == WAIT_OBJECT_0 ? OK : -1;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800518 }
519} WinCondition;
520
521/*
522 * Constructor. Set up the WinCondition stuff.
523 */
524Condition::Condition()
525{
526 WinCondition* condState = new WinCondition;
527
528 condState->waitersCount = 0;
529 condState->wasBroadcast = false;
530 // semaphore: no security, initial value of 0
531 condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
532 InitializeCriticalSection(&condState->waitersCountLock);
533 // auto-reset event, not signaled initially
534 condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
535 // used so we don't have to lock external mutex on signal/broadcast
536 condState->internalMutex = CreateMutex(NULL, FALSE, NULL);
537
538 mState = condState;
539}
540
541/*
542 * Destructor. Free Windows resources as well as our allocated storage.
543 */
544Condition::~Condition()
545{
546 WinCondition* condState = (WinCondition*) mState;
547 if (condState != NULL) {
548 CloseHandle(condState->sema);
549 CloseHandle(condState->waitersDone);
550 delete condState;
551 }
552}
553
554
555status_t Condition::wait(Mutex& mutex)
556{
557 WinCondition* condState = (WinCondition*) mState;
558 HANDLE hMutex = (HANDLE) mutex.mState;
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800559
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800560 return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
561}
562
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800563status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
564{
David 'Digit' Turner9bafd122009-08-01 00:20:17 +0200565 WinCondition* condState = (WinCondition*) mState;
566 HANDLE hMutex = (HANDLE) mutex.mState;
567 nsecs_t absTime = systemTime()+reltime;
568
569 return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800570}
571
572/*
573 * Signal the condition variable, allowing one thread to continue.
574 */
575void Condition::signal()
576{
577 WinCondition* condState = (WinCondition*) mState;
578
579 // Lock the internal mutex. This ensures that we don't clash with
580 // broadcast().
581 WaitForSingleObject(condState->internalMutex, INFINITE);
582
583 EnterCriticalSection(&condState->waitersCountLock);
584 bool haveWaiters = (condState->waitersCount > 0);
585 LeaveCriticalSection(&condState->waitersCountLock);
586
587 // If no waiters, then this is a no-op. Otherwise, knock the semaphore
588 // down a notch.
589 if (haveWaiters)
590 ReleaseSemaphore(condState->sema, 1, 0);
591
592 // Release internal mutex.
593 ReleaseMutex(condState->internalMutex);
594}
595
596/*
597 * Signal the condition variable, allowing all threads to continue.
598 *
599 * First we have to wake up all threads waiting on the semaphore, then
600 * we wait until all of the threads have actually been woken before
601 * releasing the internal mutex. This ensures that all threads are woken.
602 */
603void Condition::broadcast()
604{
605 WinCondition* condState = (WinCondition*) mState;
606
607 // Lock the internal mutex. This keeps the guys we're waking up
608 // from getting too far.
609 WaitForSingleObject(condState->internalMutex, INFINITE);
610
611 EnterCriticalSection(&condState->waitersCountLock);
612 bool haveWaiters = false;
613
614 if (condState->waitersCount > 0) {
615 haveWaiters = true;
616 condState->wasBroadcast = true;
617 }
618
619 if (haveWaiters) {
620 // Wake up all the waiters.
621 ReleaseSemaphore(condState->sema, condState->waitersCount, 0);
622
623 LeaveCriticalSection(&condState->waitersCountLock);
624
625 // Wait for all awakened threads to acquire the counting semaphore.
626 // The last guy who was waiting sets this.
627 WaitForSingleObject(condState->waitersDone, INFINITE);
628
629 // Reset wasBroadcast. (No crit section needed because nobody
630 // else can wake up to poke at it.)
631 condState->wasBroadcast = 0;
632 } else {
633 // nothing to do
634 LeaveCriticalSection(&condState->waitersCountLock);
635 }
636
637 // Release internal mutex.
638 ReleaseMutex(condState->internalMutex);
639}
640
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800641#endif // !defined(_WIN32)
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800642
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800643// ----------------------------------------------------------------------------
644
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800645/*
646 * This is our thread object!
647 */
648
649Thread::Thread(bool canCallJava)
Elliott Hughes643268f2018-10-08 11:10:11 -0700650 : mCanCallJava(canCallJava),
651 mThread(thread_id_t(-1)),
652 mLock("Thread::mLock"),
653 mStatus(OK),
654 mExitPending(false),
655 mRunning(false)
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700656#if defined(__ANDROID__)
Elliott Hughes643268f2018-10-08 11:10:11 -0700657 ,
658 mTid(-1)
Glenn Kasten966a48f2011-02-01 11:32:29 -0800659#endif
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800660{
661}
662
663Thread::~Thread()
664{
665}
666
667status_t Thread::readyToRun()
668{
Elliott Hughes643268f2018-10-08 11:10:11 -0700669 return OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800670}
671
672status_t Thread::run(const char* name, int32_t priority, size_t stack)
673{
Brian Carlstrome71b9142016-03-12 16:08:12 -0800674 LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");
675
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800676 Mutex::Autolock _l(mLock);
677
678 if (mRunning) {
679 // thread already started
680 return INVALID_OPERATION;
681 }
682
683 // reset status and exitPending to their default value, so we can
684 // try again after an error happened (either below, or in readyToRun())
Elliott Hughes643268f2018-10-08 11:10:11 -0700685 mStatus = OK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800686 mExitPending = false;
687 mThread = thread_id_t(-1);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800688
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800689 // hold a strong reference on ourself
Steven Morelanda06e68c2021-04-27 00:09:23 +0000690 mHoldSelf = sp<Thread>::fromExisting(this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800691
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800692 mRunning = true;
693
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800694 bool res;
695 if (mCanCallJava) {
696 res = createThreadEtc(_threadLoop,
697 this, name, priority, stack, &mThread);
698 } else {
699 res = androidCreateRawThreadEtc(_threadLoop,
700 this, name, priority, stack, &mThread);
701 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800702
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800703 if (res == false) {
704 mStatus = UNKNOWN_ERROR; // something happened!
705 mRunning = false;
706 mThread = thread_id_t(-1);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800707 mHoldSelf.clear(); // "this" may have gone away after this.
708
709 return UNKNOWN_ERROR;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800710 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800711
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800712 // Do not refer to mStatus here: The thread is already running (may, in fact
Elliott Hughes643268f2018-10-08 11:10:11 -0700713 // already have exited with a valid mStatus result). The OK indication
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800714 // here merely indicates successfully starting the thread and does not
715 // imply successful termination/execution.
Elliott Hughes643268f2018-10-08 11:10:11 -0700716 return OK;
Glenn Kasten966a48f2011-02-01 11:32:29 -0800717
718 // Exiting scope of mLock is a memory barrier and allows new thread to run
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800719}
720
721int Thread::_threadLoop(void* user)
722{
723 Thread* const self = static_cast<Thread*>(user);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800724
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800725 sp<Thread> strong(self->mHoldSelf);
726 wp<Thread> weak(strong);
727 self->mHoldSelf.clear();
728
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700729#if defined(__ANDROID__)
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700730 // this is very useful for debugging with gdb
731 self->mTid = gettid();
732#endif
733
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800734 bool first = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800735
736 do {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800737 bool result;
738 if (first) {
739 first = false;
740 self->mStatus = self->readyToRun();
Elliott Hughes643268f2018-10-08 11:10:11 -0700741 result = (self->mStatus == OK);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800742
Glenn Kasten966a48f2011-02-01 11:32:29 -0800743 if (result && !self->exitPending()) {
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800744 // Binder threads (and maybe others) rely on threadLoop
745 // running at least once after a successful ::readyToRun()
746 // (unless, of course, the thread has already been asked to exit
747 // at that point).
748 // This is because threads are essentially used like this:
749 // (new ThreadSubclass())->run();
750 // The caller therefore does not retain a strong reference to
751 // the thread and the thread would simply disappear after the
752 // successful ::readyToRun() call instead of entering the
753 // threadLoop at least once.
754 result = self->threadLoop();
755 }
756 } else {
757 result = self->threadLoop();
758 }
759
Glenn Kasten966a48f2011-02-01 11:32:29 -0800760 // establish a scope for mLock
761 {
762 Mutex::Autolock _l(self->mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800763 if (result == false || self->mExitPending) {
764 self->mExitPending = true;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800765 self->mRunning = false;
Eric Laurentfe2c4632011-01-04 11:58:04 -0800766 // clear thread ID so that requestExitAndWait() does not exit if
767 // called by a new thread using the same thread ID as this one.
768 self->mThread = thread_id_t(-1);
Glenn Kasten966a48f2011-02-01 11:32:29 -0800769 // note that interested observers blocked in requestExitAndWait are
770 // awoken by broadcast, but blocked on mLock until break exits scope
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700771 self->mThreadExitedCondition.broadcast();
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800772 break;
773 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800774 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800775
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800776 // Release our strong reference, to let a chance to the thread
777 // to die a peaceful death.
778 strong.clear();
Mathias Agopian51ce3ad2009-09-09 02:38:13 -0700779 // And immediately, re-acquire a strong reference for the next loop
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800780 strong = weak.promote();
Yi Konge1731a42018-07-16 18:11:34 -0700781 } while(strong != nullptr);
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800782
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800783 return 0;
784}
785
786void Thread::requestExit()
787{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800788 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800789 mExitPending = true;
790}
791
792status_t Thread::requestExitAndWait()
793{
Glenn Kastena538e262011-06-02 08:59:28 -0700794 Mutex::Autolock _l(mLock);
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800795 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000796 ALOGW(
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800797 "Thread (this=%p): don't call waitForExit() from this "
798 "Thread object's thread. It's a guaranteed deadlock!",
799 this);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800800
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800801 return WOULD_BLOCK;
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800802 }
Yabin Cui4a6e5a32015-01-26 19:48:54 -0800803
Glenn Kastena538e262011-06-02 08:59:28 -0700804 mExitPending = true;
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800805
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800806 while (mRunning == true) {
807 mThreadExitedCondition.wait(mLock);
808 }
Glenn Kasten966a48f2011-02-01 11:32:29 -0800809 // This next line is probably not needed any more, but is being left for
810 // historical reference. Note that each interested party will clear flag.
The Android Open Source Project7a4c8392009-03-05 14:34:35 -0800811 mExitPending = false;
812
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800813 return mStatus;
814}
815
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700816status_t Thread::join()
817{
818 Mutex::Autolock _l(mLock);
819 if (mThread == getThreadId()) {
Steve Block61d341b2012-01-05 23:22:43 +0000820 ALOGW(
Glenn Kasten6839e8e2011-06-23 12:55:29 -0700821 "Thread (this=%p): don't call join() from this "
822 "Thread object's thread. It's a guaranteed deadlock!",
823 this);
824
825 return WOULD_BLOCK;
826 }
827
828 while (mRunning == true) {
829 mThreadExitedCondition.wait(mLock);
830 }
831
832 return mStatus;
833}
834
Romain Guy31ba37f2013-03-11 14:34:56 -0700835bool Thread::isRunning() const {
836 Mutex::Autolock _l(mLock);
837 return mRunning;
838}
839
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700840#if defined(__ANDROID__)
Glenn Kastend731f072011-07-11 15:59:22 -0700841pid_t Thread::getTid() const
842{
843 // mTid is not defined until the child initializes it, and the caller may need it earlier
844 Mutex::Autolock _l(mLock);
845 pid_t tid;
846 if (mRunning) {
847 pthread_t pthread = android_thread_id_t_to_pthread(mThread);
Elliott Hughes7bf5f202014-09-12 10:19:08 -0700848 tid = pthread_gettid_np(pthread);
Glenn Kastend731f072011-07-11 15:59:22 -0700849 } else {
850 ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
851 tid = -1;
852 }
853 return tid;
854}
855#endif
856
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800857bool Thread::exitPending() const
858{
Glenn Kasten966a48f2011-02-01 11:32:29 -0800859 Mutex::Autolock _l(mLock);
The Android Open Source Projectcbb10112009-03-03 19:31:44 -0800860 return mExitPending;
861}
862
863
864
865}; // namespace android