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