The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1 | /* |
| 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 Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 17 | // #define LOG_NDEBUG 0 |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 18 | #define LOG_TAG "libutils.threads" |
| 19 | |
| 20 | #include <utils/threads.h> |
| 21 | #include <utils/Log.h> |
| 22 | |
Dianne Hackborn | 887f355 | 2009-12-07 17:59:37 -0800 | [diff] [blame] | 23 | #include <cutils/sched_policy.h> |
| 24 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 25 | #include <stdio.h> |
| 26 | #include <stdlib.h> |
| 27 | #include <memory.h> |
| 28 | #include <errno.h> |
| 29 | #include <assert.h> |
| 30 | #include <unistd.h> |
| 31 | |
| 32 | #if defined(HAVE_PTHREADS) |
| 33 | # include <pthread.h> |
| 34 | # include <sched.h> |
| 35 | # include <sys/resource.h> |
| 36 | #elif defined(HAVE_WIN32_THREADS) |
| 37 | # include <windows.h> |
| 38 | # include <stdint.h> |
| 39 | # include <process.h> |
| 40 | # define HAVE_CREATETHREAD // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW |
| 41 | #endif |
| 42 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 43 | #if defined(HAVE_PRCTL) |
| 44 | #include <sys/prctl.h> |
| 45 | #endif |
| 46 | |
| 47 | /* |
| 48 | * =========================================================================== |
| 49 | * Thread wrappers |
| 50 | * =========================================================================== |
| 51 | */ |
| 52 | |
| 53 | using namespace android; |
| 54 | |
| 55 | // ---------------------------------------------------------------------------- |
| 56 | #if defined(HAVE_PTHREADS) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 57 | // ---------------------------------------------------------------------------- |
| 58 | |
| 59 | /* |
| 60 | * Create and run a new thead. |
| 61 | * |
| 62 | * We create it "detached", so it cleans up after itself. |
| 63 | */ |
| 64 | |
| 65 | typedef void* (*android_pthread_entry)(void*); |
| 66 | |
| 67 | struct thread_data_t { |
| 68 | thread_func_t entryFunction; |
| 69 | void* userData; |
| 70 | int priority; |
| 71 | char * threadName; |
| 72 | |
| 73 | // we use this trampoline when we need to set the priority with |
| 74 | // nice/setpriority. |
| 75 | static int trampoline(const thread_data_t* t) { |
| 76 | thread_func_t f = t->entryFunction; |
| 77 | void* u = t->userData; |
| 78 | int prio = t->priority; |
| 79 | char * name = t->threadName; |
| 80 | delete t; |
| 81 | setpriority(PRIO_PROCESS, 0, prio); |
| 82 | if (name) { |
| 83 | #if defined(HAVE_PRCTL) |
| 84 | // Mac OS doesn't have this, and we build libutil for the host too |
| 85 | int hasAt = 0; |
| 86 | int hasDot = 0; |
| 87 | char *s = name; |
| 88 | while (*s) { |
| 89 | if (*s == '.') hasDot = 1; |
| 90 | else if (*s == '@') hasAt = 1; |
| 91 | s++; |
| 92 | } |
| 93 | int len = s - name; |
| 94 | if (len < 15 || hasAt || !hasDot) { |
| 95 | s = name; |
| 96 | } else { |
| 97 | s = name + len - 15; |
| 98 | } |
| 99 | prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); |
| 100 | #endif |
| 101 | free(name); |
| 102 | } |
| 103 | return f(u); |
| 104 | } |
| 105 | }; |
| 106 | |
| 107 | int androidCreateRawThreadEtc(android_thread_func_t entryFunction, |
| 108 | void *userData, |
| 109 | const char* threadName, |
| 110 | int32_t threadPriority, |
| 111 | size_t threadStackSize, |
| 112 | android_thread_id_t *threadId) |
| 113 | { |
| 114 | pthread_attr_t attr; |
| 115 | pthread_attr_init(&attr); |
| 116 | pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); |
| 117 | |
| 118 | #ifdef HAVE_ANDROID_OS /* valgrind is rejecting RT-priority create reqs */ |
| 119 | if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) { |
| 120 | // We could avoid the trampoline if there was a way to get to the |
| 121 | // android_thread_id_t (pid) from pthread_t |
| 122 | thread_data_t* t = new thread_data_t; |
| 123 | t->priority = threadPriority; |
| 124 | t->threadName = threadName ? strdup(threadName) : NULL; |
| 125 | t->entryFunction = entryFunction; |
| 126 | t->userData = userData; |
| 127 | entryFunction = (android_thread_func_t)&thread_data_t::trampoline; |
| 128 | userData = t; |
| 129 | } |
| 130 | #endif |
| 131 | |
| 132 | if (threadStackSize) { |
| 133 | pthread_attr_setstacksize(&attr, threadStackSize); |
| 134 | } |
| 135 | |
| 136 | errno = 0; |
| 137 | pthread_t thread; |
| 138 | int result = pthread_create(&thread, &attr, |
| 139 | (android_pthread_entry)entryFunction, userData); |
| 140 | if (result != 0) { |
| 141 | LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n" |
| 142 | "(android threadPriority=%d)", |
| 143 | entryFunction, result, errno, threadPriority); |
| 144 | return 0; |
| 145 | } |
| 146 | |
| 147 | if (threadId != NULL) { |
| 148 | *threadId = (android_thread_id_t)thread; // XXX: this is not portable |
| 149 | } |
| 150 | return 1; |
| 151 | } |
| 152 | |
| 153 | android_thread_id_t androidGetThreadId() |
| 154 | { |
| 155 | return (android_thread_id_t)pthread_self(); |
| 156 | } |
| 157 | |
| 158 | // ---------------------------------------------------------------------------- |
| 159 | #elif defined(HAVE_WIN32_THREADS) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 160 | // ---------------------------------------------------------------------------- |
| 161 | |
| 162 | /* |
| 163 | * Trampoline to make us __stdcall-compliant. |
| 164 | * |
| 165 | * We're expected to delete "vDetails" when we're done. |
| 166 | */ |
| 167 | struct threadDetails { |
| 168 | int (*func)(void*); |
| 169 | void* arg; |
| 170 | }; |
| 171 | static __stdcall unsigned int threadIntermediary(void* vDetails) |
| 172 | { |
| 173 | struct threadDetails* pDetails = (struct threadDetails*) vDetails; |
| 174 | int result; |
| 175 | |
| 176 | result = (*(pDetails->func))(pDetails->arg); |
| 177 | |
| 178 | delete pDetails; |
| 179 | |
| 180 | LOG(LOG_VERBOSE, "thread", "thread exiting\n"); |
| 181 | return (unsigned int) result; |
| 182 | } |
| 183 | |
| 184 | /* |
| 185 | * Create and run a new thread. |
| 186 | */ |
| 187 | static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id) |
| 188 | { |
| 189 | HANDLE hThread; |
| 190 | struct threadDetails* pDetails = new threadDetails; // must be on heap |
| 191 | unsigned int thrdaddr; |
| 192 | |
| 193 | pDetails->func = fn; |
| 194 | pDetails->arg = arg; |
| 195 | |
| 196 | #if defined(HAVE__BEGINTHREADEX) |
| 197 | hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0, |
| 198 | &thrdaddr); |
| 199 | if (hThread == 0) |
| 200 | #elif defined(HAVE_CREATETHREAD) |
| 201 | hThread = CreateThread(NULL, 0, |
| 202 | (LPTHREAD_START_ROUTINE) threadIntermediary, |
| 203 | (void*) pDetails, 0, (DWORD*) &thrdaddr); |
| 204 | if (hThread == NULL) |
| 205 | #endif |
| 206 | { |
| 207 | LOG(LOG_WARN, "thread", "WARNING: thread create failed\n"); |
| 208 | return false; |
| 209 | } |
| 210 | |
| 211 | #if defined(HAVE_CREATETHREAD) |
| 212 | /* close the management handle */ |
| 213 | CloseHandle(hThread); |
| 214 | #endif |
| 215 | |
| 216 | if (id != NULL) { |
| 217 | *id = (android_thread_id_t)thrdaddr; |
| 218 | } |
| 219 | |
| 220 | return true; |
| 221 | } |
| 222 | |
| 223 | int androidCreateRawThreadEtc(android_thread_func_t fn, |
| 224 | void *userData, |
| 225 | const char* threadName, |
| 226 | int32_t threadPriority, |
| 227 | size_t threadStackSize, |
| 228 | android_thread_id_t *threadId) |
| 229 | { |
| 230 | return doCreateThread( fn, userData, threadId); |
| 231 | } |
| 232 | |
| 233 | android_thread_id_t androidGetThreadId() |
| 234 | { |
| 235 | return (android_thread_id_t)GetCurrentThreadId(); |
| 236 | } |
| 237 | |
| 238 | // ---------------------------------------------------------------------------- |
| 239 | #else |
| 240 | #error "Threads not supported" |
| 241 | #endif |
| 242 | |
| 243 | // ---------------------------------------------------------------------------- |
| 244 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 245 | int androidCreateThread(android_thread_func_t fn, void* arg) |
| 246 | { |
| 247 | return createThreadEtc(fn, arg); |
| 248 | } |
| 249 | |
| 250 | int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id) |
| 251 | { |
| 252 | return createThreadEtc(fn, arg, "android:unnamed_thread", |
| 253 | PRIORITY_DEFAULT, 0, id); |
| 254 | } |
| 255 | |
| 256 | static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc; |
| 257 | |
| 258 | int androidCreateThreadEtc(android_thread_func_t entryFunction, |
| 259 | void *userData, |
| 260 | const char* threadName, |
| 261 | int32_t threadPriority, |
| 262 | size_t threadStackSize, |
| 263 | android_thread_id_t *threadId) |
| 264 | { |
| 265 | return gCreateThreadFn(entryFunction, userData, threadName, |
| 266 | threadPriority, threadStackSize, threadId); |
| 267 | } |
| 268 | |
| 269 | void androidSetCreateThreadFunc(android_create_thread_fn func) |
| 270 | { |
| 271 | gCreateThreadFn = func; |
| 272 | } |
| 273 | |
Dianne Hackborn | 887f355 | 2009-12-07 17:59:37 -0800 | [diff] [blame] | 274 | pid_t androidGetTid() |
| 275 | { |
| 276 | #ifdef HAVE_GETTID |
| 277 | return gettid(); |
| 278 | #else |
| 279 | return getpid(); |
| 280 | #endif |
| 281 | } |
| 282 | |
| 283 | int androidSetThreadSchedulingGroup(pid_t tid, int grp) |
| 284 | { |
| 285 | if (grp > ANDROID_TGROUP_MAX || grp < 0) { |
| 286 | return BAD_VALUE; |
| 287 | } |
| 288 | |
Dianne Hackborn | afbeb31 | 2009-12-08 19:45:59 -0800 | [diff] [blame] | 289 | #if defined(HAVE_PTHREADS) |
Dianne Hackborn | 887f355 | 2009-12-07 17:59:37 -0800 | [diff] [blame] | 290 | if (set_sched_policy(tid, (grp == ANDROID_TGROUP_BG_NONINTERACT) ? |
| 291 | SP_BACKGROUND : SP_FOREGROUND)) { |
| 292 | return PERMISSION_DENIED; |
| 293 | } |
Dianne Hackborn | afbeb31 | 2009-12-08 19:45:59 -0800 | [diff] [blame] | 294 | #endif |
Dianne Hackborn | 887f355 | 2009-12-07 17:59:37 -0800 | [diff] [blame] | 295 | |
| 296 | return NO_ERROR; |
| 297 | } |
| 298 | |
| 299 | int androidSetThreadPriority(pid_t tid, int pri) |
| 300 | { |
| 301 | int rc = 0; |
Dianne Hackborn | afbeb31 | 2009-12-08 19:45:59 -0800 | [diff] [blame] | 302 | |
| 303 | #if defined(HAVE_PTHREADS) |
Dianne Hackborn | 887f355 | 2009-12-07 17:59:37 -0800 | [diff] [blame] | 304 | int lasterr = 0; |
| 305 | |
| 306 | if (pri >= ANDROID_PRIORITY_BACKGROUND) { |
| 307 | rc = set_sched_policy(tid, SP_BACKGROUND); |
| 308 | } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) { |
| 309 | rc = set_sched_policy(tid, SP_FOREGROUND); |
| 310 | } |
| 311 | |
| 312 | if (rc) { |
| 313 | lasterr = errno; |
| 314 | } |
| 315 | |
| 316 | if (setpriority(PRIO_PROCESS, tid, pri) < 0) { |
| 317 | rc = INVALID_OPERATION; |
| 318 | } else { |
| 319 | errno = lasterr; |
| 320 | } |
Dianne Hackborn | 06fb2c1 | 2009-12-08 16:38:01 -0800 | [diff] [blame] | 321 | #endif |
Dianne Hackborn | 887f355 | 2009-12-07 17:59:37 -0800 | [diff] [blame] | 322 | |
| 323 | return rc; |
| 324 | } |
| 325 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 326 | namespace android { |
| 327 | |
| 328 | /* |
| 329 | * =========================================================================== |
| 330 | * Mutex class |
| 331 | * =========================================================================== |
| 332 | */ |
| 333 | |
Mathias Agopian | b1c4ca5 | 2009-07-12 23:11:20 -0700 | [diff] [blame] | 334 | #if defined(HAVE_PTHREADS) |
| 335 | // implemented as inlines in threads.h |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 336 | #elif defined(HAVE_WIN32_THREADS) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 337 | |
| 338 | Mutex::Mutex() |
| 339 | { |
| 340 | HANDLE hMutex; |
| 341 | |
| 342 | assert(sizeof(hMutex) == sizeof(mState)); |
| 343 | |
| 344 | hMutex = CreateMutex(NULL, FALSE, NULL); |
| 345 | mState = (void*) hMutex; |
| 346 | } |
| 347 | |
| 348 | Mutex::Mutex(const char* name) |
| 349 | { |
| 350 | // XXX: name not used for now |
| 351 | HANDLE hMutex; |
| 352 | |
David 'Digit' Turner | 078a275 | 2009-08-01 00:20:17 +0200 | [diff] [blame] | 353 | assert(sizeof(hMutex) == sizeof(mState)); |
| 354 | |
| 355 | hMutex = CreateMutex(NULL, FALSE, NULL); |
| 356 | mState = (void*) hMutex; |
| 357 | } |
| 358 | |
| 359 | Mutex::Mutex(int type, const char* name) |
| 360 | { |
| 361 | // XXX: type and name not used for now |
| 362 | HANDLE hMutex; |
| 363 | |
| 364 | assert(sizeof(hMutex) == sizeof(mState)); |
| 365 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 366 | hMutex = CreateMutex(NULL, FALSE, NULL); |
| 367 | mState = (void*) hMutex; |
| 368 | } |
| 369 | |
| 370 | Mutex::~Mutex() |
| 371 | { |
| 372 | CloseHandle((HANDLE) mState); |
| 373 | } |
| 374 | |
| 375 | status_t Mutex::lock() |
| 376 | { |
| 377 | DWORD dwWaitResult; |
| 378 | dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE); |
| 379 | return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR; |
| 380 | } |
| 381 | |
| 382 | void Mutex::unlock() |
| 383 | { |
| 384 | if (!ReleaseMutex((HANDLE) mState)) |
| 385 | LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n"); |
| 386 | } |
| 387 | |
| 388 | status_t Mutex::tryLock() |
| 389 | { |
| 390 | DWORD dwWaitResult; |
| 391 | |
| 392 | dwWaitResult = WaitForSingleObject((HANDLE) mState, 0); |
| 393 | if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT) |
| 394 | LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n"); |
| 395 | return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1; |
| 396 | } |
| 397 | |
| 398 | #else |
| 399 | #error "Somebody forgot to implement threads for this platform." |
| 400 | #endif |
| 401 | |
| 402 | |
| 403 | /* |
| 404 | * =========================================================================== |
| 405 | * Condition class |
| 406 | * =========================================================================== |
| 407 | */ |
| 408 | |
Mathias Agopian | b1c4ca5 | 2009-07-12 23:11:20 -0700 | [diff] [blame] | 409 | #if defined(HAVE_PTHREADS) |
| 410 | // implemented as inlines in threads.h |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 411 | #elif defined(HAVE_WIN32_THREADS) |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 412 | |
| 413 | /* |
| 414 | * Windows doesn't have a condition variable solution. It's possible |
| 415 | * to create one, but it's easy to get it wrong. For a discussion, and |
| 416 | * the origin of this implementation, see: |
| 417 | * |
| 418 | * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html |
| 419 | * |
| 420 | * The implementation shown on the page does NOT follow POSIX semantics. |
| 421 | * As an optimization they require acquiring the external mutex before |
| 422 | * calling signal() and broadcast(), whereas POSIX only requires grabbing |
| 423 | * it before calling wait(). The implementation here has been un-optimized |
| 424 | * to have the correct behavior. |
| 425 | */ |
| 426 | typedef struct WinCondition { |
| 427 | // Number of waiting threads. |
| 428 | int waitersCount; |
| 429 | |
| 430 | // Serialize access to waitersCount. |
| 431 | CRITICAL_SECTION waitersCountLock; |
| 432 | |
| 433 | // Semaphore used to queue up threads waiting for the condition to |
| 434 | // become signaled. |
| 435 | HANDLE sema; |
| 436 | |
| 437 | // An auto-reset event used by the broadcast/signal thread to wait |
| 438 | // for all the waiting thread(s) to wake up and be released from |
| 439 | // the semaphore. |
| 440 | HANDLE waitersDone; |
| 441 | |
| 442 | // This mutex wouldn't be necessary if we required that the caller |
| 443 | // lock the external mutex before calling signal() and broadcast(). |
| 444 | // I'm trying to mimic pthread semantics though. |
| 445 | HANDLE internalMutex; |
| 446 | |
| 447 | // Keeps track of whether we were broadcasting or signaling. This |
| 448 | // allows us to optimize the code if we're just signaling. |
| 449 | bool wasBroadcast; |
| 450 | |
| 451 | status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime) |
| 452 | { |
| 453 | // Increment the wait count, avoiding race conditions. |
| 454 | EnterCriticalSection(&condState->waitersCountLock); |
| 455 | condState->waitersCount++; |
| 456 | //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n", |
| 457 | // condState->waitersCount, getThreadId()); |
| 458 | LeaveCriticalSection(&condState->waitersCountLock); |
| 459 | |
| 460 | DWORD timeout = INFINITE; |
| 461 | if (abstime) { |
| 462 | nsecs_t reltime = *abstime - systemTime(); |
| 463 | if (reltime < 0) |
| 464 | reltime = 0; |
| 465 | timeout = reltime/1000000; |
| 466 | } |
| 467 | |
| 468 | // Atomically release the external mutex and wait on the semaphore. |
| 469 | DWORD res = |
| 470 | SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE); |
| 471 | |
| 472 | //printf("+++ wait: awake (tid=%ld)\n", getThreadId()); |
| 473 | |
| 474 | // Reacquire lock to avoid race conditions. |
| 475 | EnterCriticalSection(&condState->waitersCountLock); |
| 476 | |
| 477 | // No longer waiting. |
| 478 | condState->waitersCount--; |
| 479 | |
| 480 | // Check to see if we're the last waiter after a broadcast. |
| 481 | bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0); |
| 482 | |
| 483 | //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n", |
| 484 | // lastWaiter, condState->wasBroadcast, condState->waitersCount); |
| 485 | |
| 486 | LeaveCriticalSection(&condState->waitersCountLock); |
| 487 | |
| 488 | // If we're the last waiter thread during this particular broadcast |
| 489 | // then signal broadcast() that we're all awake. It'll drop the |
| 490 | // internal mutex. |
| 491 | if (lastWaiter) { |
| 492 | // Atomically signal the "waitersDone" event and wait until we |
| 493 | // can acquire the internal mutex. We want to do this in one step |
| 494 | // because it ensures that everybody is in the mutex FIFO before |
| 495 | // any thread has a chance to run. Without it, another thread |
| 496 | // could wake up, do work, and hop back in ahead of us. |
| 497 | SignalObjectAndWait(condState->waitersDone, condState->internalMutex, |
| 498 | INFINITE, FALSE); |
| 499 | } else { |
| 500 | // Grab the internal mutex. |
| 501 | WaitForSingleObject(condState->internalMutex, INFINITE); |
| 502 | } |
| 503 | |
| 504 | // Release the internal and grab the external. |
| 505 | ReleaseMutex(condState->internalMutex); |
| 506 | WaitForSingleObject(hMutex, INFINITE); |
| 507 | |
| 508 | return res == WAIT_OBJECT_0 ? NO_ERROR : -1; |
| 509 | } |
| 510 | } WinCondition; |
| 511 | |
| 512 | /* |
| 513 | * Constructor. Set up the WinCondition stuff. |
| 514 | */ |
| 515 | Condition::Condition() |
| 516 | { |
| 517 | WinCondition* condState = new WinCondition; |
| 518 | |
| 519 | condState->waitersCount = 0; |
| 520 | condState->wasBroadcast = false; |
| 521 | // semaphore: no security, initial value of 0 |
| 522 | condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL); |
| 523 | InitializeCriticalSection(&condState->waitersCountLock); |
| 524 | // auto-reset event, not signaled initially |
| 525 | condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL); |
| 526 | // used so we don't have to lock external mutex on signal/broadcast |
| 527 | condState->internalMutex = CreateMutex(NULL, FALSE, NULL); |
| 528 | |
| 529 | mState = condState; |
| 530 | } |
| 531 | |
| 532 | /* |
| 533 | * Destructor. Free Windows resources as well as our allocated storage. |
| 534 | */ |
| 535 | Condition::~Condition() |
| 536 | { |
| 537 | WinCondition* condState = (WinCondition*) mState; |
| 538 | if (condState != NULL) { |
| 539 | CloseHandle(condState->sema); |
| 540 | CloseHandle(condState->waitersDone); |
| 541 | delete condState; |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | |
| 546 | status_t Condition::wait(Mutex& mutex) |
| 547 | { |
| 548 | WinCondition* condState = (WinCondition*) mState; |
| 549 | HANDLE hMutex = (HANDLE) mutex.mState; |
| 550 | |
| 551 | return ((WinCondition*)mState)->wait(condState, hMutex, NULL); |
| 552 | } |
| 553 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 554 | status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) |
| 555 | { |
David 'Digit' Turner | 078a275 | 2009-08-01 00:20:17 +0200 | [diff] [blame] | 556 | WinCondition* condState = (WinCondition*) mState; |
| 557 | HANDLE hMutex = (HANDLE) mutex.mState; |
| 558 | nsecs_t absTime = systemTime()+reltime; |
| 559 | |
| 560 | return ((WinCondition*)mState)->wait(condState, hMutex, &absTime); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 561 | } |
| 562 | |
| 563 | /* |
| 564 | * Signal the condition variable, allowing one thread to continue. |
| 565 | */ |
| 566 | void Condition::signal() |
| 567 | { |
| 568 | WinCondition* condState = (WinCondition*) mState; |
| 569 | |
| 570 | // Lock the internal mutex. This ensures that we don't clash with |
| 571 | // broadcast(). |
| 572 | WaitForSingleObject(condState->internalMutex, INFINITE); |
| 573 | |
| 574 | EnterCriticalSection(&condState->waitersCountLock); |
| 575 | bool haveWaiters = (condState->waitersCount > 0); |
| 576 | LeaveCriticalSection(&condState->waitersCountLock); |
| 577 | |
| 578 | // If no waiters, then this is a no-op. Otherwise, knock the semaphore |
| 579 | // down a notch. |
| 580 | if (haveWaiters) |
| 581 | ReleaseSemaphore(condState->sema, 1, 0); |
| 582 | |
| 583 | // Release internal mutex. |
| 584 | ReleaseMutex(condState->internalMutex); |
| 585 | } |
| 586 | |
| 587 | /* |
| 588 | * Signal the condition variable, allowing all threads to continue. |
| 589 | * |
| 590 | * First we have to wake up all threads waiting on the semaphore, then |
| 591 | * we wait until all of the threads have actually been woken before |
| 592 | * releasing the internal mutex. This ensures that all threads are woken. |
| 593 | */ |
| 594 | void Condition::broadcast() |
| 595 | { |
| 596 | WinCondition* condState = (WinCondition*) mState; |
| 597 | |
| 598 | // Lock the internal mutex. This keeps the guys we're waking up |
| 599 | // from getting too far. |
| 600 | WaitForSingleObject(condState->internalMutex, INFINITE); |
| 601 | |
| 602 | EnterCriticalSection(&condState->waitersCountLock); |
| 603 | bool haveWaiters = false; |
| 604 | |
| 605 | if (condState->waitersCount > 0) { |
| 606 | haveWaiters = true; |
| 607 | condState->wasBroadcast = true; |
| 608 | } |
| 609 | |
| 610 | if (haveWaiters) { |
| 611 | // Wake up all the waiters. |
| 612 | ReleaseSemaphore(condState->sema, condState->waitersCount, 0); |
| 613 | |
| 614 | LeaveCriticalSection(&condState->waitersCountLock); |
| 615 | |
| 616 | // Wait for all awakened threads to acquire the counting semaphore. |
| 617 | // The last guy who was waiting sets this. |
| 618 | WaitForSingleObject(condState->waitersDone, INFINITE); |
| 619 | |
| 620 | // Reset wasBroadcast. (No crit section needed because nobody |
| 621 | // else can wake up to poke at it.) |
| 622 | condState->wasBroadcast = 0; |
| 623 | } else { |
| 624 | // nothing to do |
| 625 | LeaveCriticalSection(&condState->waitersCountLock); |
| 626 | } |
| 627 | |
| 628 | // Release internal mutex. |
| 629 | ReleaseMutex(condState->internalMutex); |
| 630 | } |
| 631 | |
| 632 | #else |
| 633 | #error "condition variables not supported on this platform" |
| 634 | #endif |
| 635 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 636 | // ---------------------------------------------------------------------------- |
| 637 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 638 | /* |
| 639 | * This is our thread object! |
| 640 | */ |
| 641 | |
| 642 | Thread::Thread(bool canCallJava) |
| 643 | : mCanCallJava(canCallJava), |
| 644 | mThread(thread_id_t(-1)), |
| 645 | mLock("Thread::mLock"), |
| 646 | mStatus(NO_ERROR), |
| 647 | mExitPending(false), mRunning(false) |
| 648 | { |
| 649 | } |
| 650 | |
| 651 | Thread::~Thread() |
| 652 | { |
| 653 | } |
| 654 | |
| 655 | status_t Thread::readyToRun() |
| 656 | { |
| 657 | return NO_ERROR; |
| 658 | } |
| 659 | |
| 660 | status_t Thread::run(const char* name, int32_t priority, size_t stack) |
| 661 | { |
| 662 | Mutex::Autolock _l(mLock); |
| 663 | |
| 664 | if (mRunning) { |
| 665 | // thread already started |
| 666 | return INVALID_OPERATION; |
| 667 | } |
| 668 | |
| 669 | // reset status and exitPending to their default value, so we can |
| 670 | // try again after an error happened (either below, or in readyToRun()) |
| 671 | mStatus = NO_ERROR; |
| 672 | mExitPending = false; |
| 673 | mThread = thread_id_t(-1); |
| 674 | |
| 675 | // hold a strong reference on ourself |
| 676 | mHoldSelf = this; |
| 677 | |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 678 | mRunning = true; |
| 679 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 680 | bool res; |
| 681 | if (mCanCallJava) { |
| 682 | res = createThreadEtc(_threadLoop, |
| 683 | this, name, priority, stack, &mThread); |
| 684 | } else { |
| 685 | res = androidCreateRawThreadEtc(_threadLoop, |
| 686 | this, name, priority, stack, &mThread); |
| 687 | } |
| 688 | |
| 689 | if (res == false) { |
| 690 | mStatus = UNKNOWN_ERROR; // something happened! |
| 691 | mRunning = false; |
| 692 | mThread = thread_id_t(-1); |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 693 | mHoldSelf.clear(); // "this" may have gone away after this. |
| 694 | |
| 695 | return UNKNOWN_ERROR; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 696 | } |
| 697 | |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 698 | // Do not refer to mStatus here: The thread is already running (may, in fact |
| 699 | // already have exited with a valid mStatus result). The NO_ERROR indication |
| 700 | // here merely indicates successfully starting the thread and does not |
| 701 | // imply successful termination/execution. |
| 702 | return NO_ERROR; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 703 | } |
| 704 | |
| 705 | int Thread::_threadLoop(void* user) |
| 706 | { |
| 707 | Thread* const self = static_cast<Thread*>(user); |
| 708 | sp<Thread> strong(self->mHoldSelf); |
| 709 | wp<Thread> weak(strong); |
| 710 | self->mHoldSelf.clear(); |
| 711 | |
Mathias Agopian | d42bd87 | 2009-09-09 02:38:13 -0700 | [diff] [blame] | 712 | #if HAVE_ANDROID_OS |
| 713 | // this is very useful for debugging with gdb |
| 714 | self->mTid = gettid(); |
| 715 | #endif |
| 716 | |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 717 | bool first = true; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 718 | |
| 719 | do { |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 720 | bool result; |
| 721 | if (first) { |
| 722 | first = false; |
| 723 | self->mStatus = self->readyToRun(); |
| 724 | result = (self->mStatus == NO_ERROR); |
| 725 | |
| 726 | if (result && !self->mExitPending) { |
| 727 | // Binder threads (and maybe others) rely on threadLoop |
| 728 | // running at least once after a successful ::readyToRun() |
| 729 | // (unless, of course, the thread has already been asked to exit |
| 730 | // at that point). |
| 731 | // This is because threads are essentially used like this: |
| 732 | // (new ThreadSubclass())->run(); |
| 733 | // The caller therefore does not retain a strong reference to |
| 734 | // the thread and the thread would simply disappear after the |
| 735 | // successful ::readyToRun() call instead of entering the |
| 736 | // threadLoop at least once. |
| 737 | result = self->threadLoop(); |
| 738 | } |
| 739 | } else { |
| 740 | result = self->threadLoop(); |
| 741 | } |
| 742 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 743 | if (result == false || self->mExitPending) { |
| 744 | self->mExitPending = true; |
| 745 | self->mLock.lock(); |
| 746 | self->mRunning = false; |
Mathias Agopian | d42bd87 | 2009-09-09 02:38:13 -0700 | [diff] [blame] | 747 | self->mThreadExitedCondition.broadcast(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 748 | self->mLock.unlock(); |
| 749 | break; |
| 750 | } |
| 751 | |
| 752 | // Release our strong reference, to let a chance to the thread |
| 753 | // to die a peaceful death. |
| 754 | strong.clear(); |
Mathias Agopian | d42bd87 | 2009-09-09 02:38:13 -0700 | [diff] [blame] | 755 | // And immediately, re-acquire a strong reference for the next loop |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 756 | strong = weak.promote(); |
| 757 | } while(strong != 0); |
| 758 | |
| 759 | return 0; |
| 760 | } |
| 761 | |
| 762 | void Thread::requestExit() |
| 763 | { |
| 764 | mExitPending = true; |
| 765 | } |
| 766 | |
| 767 | status_t Thread::requestExitAndWait() |
| 768 | { |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 769 | if (mThread == getThreadId()) { |
| 770 | LOGW( |
| 771 | "Thread (this=%p): don't call waitForExit() from this " |
| 772 | "Thread object's thread. It's a guaranteed deadlock!", |
| 773 | this); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 774 | |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 775 | return WOULD_BLOCK; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 776 | } |
The Android Open Source Project | 4df2423 | 2009-03-05 14:34:35 -0800 | [diff] [blame] | 777 | |
| 778 | requestExit(); |
| 779 | |
| 780 | Mutex::Autolock _l(mLock); |
| 781 | while (mRunning == true) { |
| 782 | mThreadExitedCondition.wait(mLock); |
| 783 | } |
| 784 | mExitPending = false; |
| 785 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 786 | return mStatus; |
| 787 | } |
| 788 | |
| 789 | bool Thread::exitPending() const |
| 790 | { |
| 791 | return mExitPending; |
| 792 | } |
| 793 | |
| 794 | |
| 795 | |
| 796 | }; // namespace android |