threads.h revision 235af97debd4b75263dfdb9e3be78e50eff2a53a
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 17#ifndef _LIBS_UTILS_THREADS_H 18#define _LIBS_UTILS_THREADS_H 19 20#include <stdint.h> 21#include <sys/types.h> 22#include <time.h> 23 24#if defined(HAVE_PTHREADS) 25# include <pthread.h> 26#endif 27 28// ------------------------------------------------------------------ 29// C API 30 31#ifdef __cplusplus 32extern "C" { 33#endif 34 35typedef void* android_thread_id_t; 36 37typedef int (*android_thread_func_t)(void*); 38 39enum { 40 /* 41 * *********************************************** 42 * ** Keep in sync with android.os.Process.java ** 43 * *********************************************** 44 * 45 * This maps directly to the "nice" priorites we use in Android. 46 * A thread priority should be chosen inverse-proportinally to 47 * the amount of work the thread is expected to do. The more work 48 * a thread will do, the less favorable priority it should get so that 49 * it doesn't starve the system. Threads not behaving properly might 50 * be "punished" by the kernel. 51 * Use the levels below when appropriate. Intermediate values are 52 * acceptable, preferably use the {MORE|LESS}_FAVORABLE constants below. 53 */ 54 ANDROID_PRIORITY_LOWEST = 19, 55 56 /* use for background tasks */ 57 ANDROID_PRIORITY_BACKGROUND = 10, 58 59 /* most threads run at normal priority */ 60 ANDROID_PRIORITY_NORMAL = 0, 61 62 /* threads currently running a UI that the user is interacting with */ 63 ANDROID_PRIORITY_FOREGROUND = -2, 64 65 /* the main UI thread has a slightly more favorable priority */ 66 ANDROID_PRIORITY_DISPLAY = -4, 67 68 /* ui service treads might want to run at a urgent display (uncommon) */ 69 ANDROID_PRIORITY_URGENT_DISPLAY = -8, 70 71 /* all normal audio threads */ 72 ANDROID_PRIORITY_AUDIO = -16, 73 74 /* service audio threads (uncommon) */ 75 ANDROID_PRIORITY_URGENT_AUDIO = -19, 76 77 /* should never be used in practice. regular process might not 78 * be allowed to use this level */ 79 ANDROID_PRIORITY_HIGHEST = -20, 80 81 ANDROID_PRIORITY_DEFAULT = ANDROID_PRIORITY_NORMAL, 82 ANDROID_PRIORITY_MORE_FAVORABLE = -1, 83 ANDROID_PRIORITY_LESS_FAVORABLE = +1, 84}; 85 86enum { 87 ANDROID_TGROUP_DEFAULT = 0, 88 ANDROID_TGROUP_BG_NONINTERACT = 1, 89 ANDROID_TGROUP_FG_BOOST = 2, 90 ANDROID_TGROUP_MAX = ANDROID_TGROUP_FG_BOOST, 91}; 92 93// Create and run a new thread. 94extern int androidCreateThread(android_thread_func_t, void *); 95 96// Create thread with lots of parameters 97extern int androidCreateThreadEtc(android_thread_func_t entryFunction, 98 void *userData, 99 const char* threadName, 100 int32_t threadPriority, 101 size_t threadStackSize, 102 android_thread_id_t *threadId); 103 104// Get some sort of unique identifier for the current thread. 105extern android_thread_id_t androidGetThreadId(); 106 107// Low-level thread creation -- never creates threads that can 108// interact with the Java VM. 109extern int androidCreateRawThreadEtc(android_thread_func_t entryFunction, 110 void *userData, 111 const char* threadName, 112 int32_t threadPriority, 113 size_t threadStackSize, 114 android_thread_id_t *threadId); 115 116// Used by the Java Runtime to control how threads are created, so that 117// they can be proper and lovely Java threads. 118typedef int (*android_create_thread_fn)(android_thread_func_t entryFunction, 119 void *userData, 120 const char* threadName, 121 int32_t threadPriority, 122 size_t threadStackSize, 123 android_thread_id_t *threadId); 124 125extern void androidSetCreateThreadFunc(android_create_thread_fn func); 126 127// ------------------------------------------------------------------ 128// Extra functions working with raw pids. 129 130// Get pid for the current thread. 131extern pid_t androidGetTid(); 132 133// Change the scheduling group of a particular thread. The group 134// should be one of the ANDROID_TGROUP constants. Returns BAD_VALUE if 135// grp is out of range, else another non-zero value with errno set if 136// the operation failed. 137extern int androidSetThreadSchedulingGroup(pid_t tid, int grp); 138 139// Change the priority AND scheduling group of a particular thread. The priority 140// should be one of the ANDROID_PRIORITY constants. Returns INVALID_OPERATION 141// if the priority set failed, else another value if just the group set failed; 142// in either case errno is set. 143extern int androidSetThreadPriority(pid_t tid, int prio); 144 145#ifdef __cplusplus 146} 147#endif 148 149// ------------------------------------------------------------------ 150// C++ API 151 152#ifdef __cplusplus 153 154#include <utils/Errors.h> 155#include <utils/RefBase.h> 156#include <utils/Timers.h> 157 158namespace android { 159 160typedef android_thread_id_t thread_id_t; 161 162typedef android_thread_func_t thread_func_t; 163 164enum { 165 PRIORITY_LOWEST = ANDROID_PRIORITY_LOWEST, 166 PRIORITY_BACKGROUND = ANDROID_PRIORITY_BACKGROUND, 167 PRIORITY_NORMAL = ANDROID_PRIORITY_NORMAL, 168 PRIORITY_FOREGROUND = ANDROID_PRIORITY_FOREGROUND, 169 PRIORITY_DISPLAY = ANDROID_PRIORITY_DISPLAY, 170 PRIORITY_URGENT_DISPLAY = ANDROID_PRIORITY_URGENT_DISPLAY, 171 PRIORITY_AUDIO = ANDROID_PRIORITY_AUDIO, 172 PRIORITY_URGENT_AUDIO = ANDROID_PRIORITY_URGENT_AUDIO, 173 PRIORITY_HIGHEST = ANDROID_PRIORITY_HIGHEST, 174 PRIORITY_DEFAULT = ANDROID_PRIORITY_DEFAULT, 175 PRIORITY_MORE_FAVORABLE = ANDROID_PRIORITY_MORE_FAVORABLE, 176 PRIORITY_LESS_FAVORABLE = ANDROID_PRIORITY_LESS_FAVORABLE, 177}; 178 179// Create and run a new thread. 180inline bool createThread(thread_func_t f, void *a) { 181 return androidCreateThread(f, a) ? true : false; 182} 183 184// Create thread with lots of parameters 185inline bool createThreadEtc(thread_func_t entryFunction, 186 void *userData, 187 const char* threadName = "android:unnamed_thread", 188 int32_t threadPriority = PRIORITY_DEFAULT, 189 size_t threadStackSize = 0, 190 thread_id_t *threadId = 0) 191{ 192 return androidCreateThreadEtc(entryFunction, userData, threadName, 193 threadPriority, threadStackSize, threadId) ? true : false; 194} 195 196// Get some sort of unique identifier for the current thread. 197inline thread_id_t getThreadId() { 198 return androidGetThreadId(); 199} 200 201/*****************************************************************************/ 202 203/* 204 * Simple mutex class. The implementation is system-dependent. 205 * 206 * The mutex must be unlocked by the thread that locked it. They are not 207 * recursive, i.e. the same thread can't lock it multiple times. 208 */ 209class Mutex { 210public: 211 enum { 212 NORMAL = 0, 213 SHARED = 1 214 }; 215 216 Mutex(); 217 Mutex(const char* name); 218 Mutex(int type, const char* name = NULL); 219 ~Mutex(); 220 221 // lock or unlock the mutex 222 status_t lock(); 223 void unlock(); 224 225 // lock if possible; returns 0 on success, error otherwise 226 status_t tryLock(); 227 228 // Manages the mutex automatically. It'll be locked when Autolock is 229 // constructed and released when Autolock goes out of scope. 230 class Autolock { 231 public: 232 inline Autolock(Mutex& mutex) : mLock(mutex) { mLock.lock(); } 233 inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); } 234 inline ~Autolock() { mLock.unlock(); } 235 private: 236 Mutex& mLock; 237 }; 238 239private: 240 friend class Condition; 241 242 // A mutex cannot be copied 243 Mutex(const Mutex&); 244 Mutex& operator = (const Mutex&); 245 246#if defined(HAVE_PTHREADS) 247 pthread_mutex_t mMutex; 248#else 249 void _init(); 250 void* mState; 251#endif 252}; 253 254#if defined(HAVE_PTHREADS) 255 256inline Mutex::Mutex() { 257 pthread_mutex_init(&mMutex, NULL); 258} 259inline Mutex::Mutex(const char* name) { 260 pthread_mutex_init(&mMutex, NULL); 261} 262inline Mutex::Mutex(int type, const char* name) { 263 if (type == SHARED) { 264 pthread_mutexattr_t attr; 265 pthread_mutexattr_init(&attr); 266 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); 267 pthread_mutex_init(&mMutex, &attr); 268 pthread_mutexattr_destroy(&attr); 269 } else { 270 pthread_mutex_init(&mMutex, NULL); 271 } 272} 273inline Mutex::~Mutex() { 274 pthread_mutex_destroy(&mMutex); 275} 276inline status_t Mutex::lock() { 277 return -pthread_mutex_lock(&mMutex); 278} 279inline void Mutex::unlock() { 280 pthread_mutex_unlock(&mMutex); 281} 282inline status_t Mutex::tryLock() { 283 return -pthread_mutex_trylock(&mMutex); 284} 285 286#endif // HAVE_PTHREADS 287 288/* 289 * Automatic mutex. Declare one of these at the top of a function. 290 * When the function returns, it will go out of scope, and release the 291 * mutex. 292 */ 293 294typedef Mutex::Autolock AutoMutex; 295 296/*****************************************************************************/ 297 298/* 299 * Condition variable class. The implementation is system-dependent. 300 * 301 * Condition variables are paired up with mutexes. Lock the mutex, 302 * call wait(), then either re-wait() if things aren't quite what you want, 303 * or unlock the mutex and continue. All threads calling wait() must 304 * use the same mutex for a given Condition. 305 */ 306class Condition { 307public: 308 Condition(); 309 ~Condition(); 310 // Wait on the condition variable. Lock the mutex before calling. 311 status_t wait(Mutex& mutex); 312 // same with relative timeout 313 status_t waitRelative(Mutex& mutex, nsecs_t reltime); 314 // Signal the condition variable, allowing one thread to continue. 315 void signal(); 316 // Signal the condition variable, allowing all threads to continue. 317 void broadcast(); 318 319private: 320#if defined(HAVE_PTHREADS) 321 pthread_cond_t mCond; 322#else 323 void* mState; 324#endif 325}; 326 327#if defined(HAVE_PTHREADS) 328 329inline Condition::Condition() { 330 pthread_cond_init(&mCond, NULL); 331} 332inline Condition::~Condition() { 333 pthread_cond_destroy(&mCond); 334} 335inline status_t Condition::wait(Mutex& mutex) { 336 return -pthread_cond_wait(&mCond, &mutex.mMutex); 337} 338inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) { 339#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE) 340 struct timespec ts; 341 ts.tv_sec = reltime/1000000000; 342 ts.tv_nsec = reltime%1000000000; 343 return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts); 344#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE 345 struct timespec ts; 346#if defined(HAVE_POSIX_CLOCKS) 347 clock_gettime(CLOCK_REALTIME, &ts); 348#else // HAVE_POSIX_CLOCKS 349 // we don't support the clocks here. 350 struct timeval t; 351 gettimeofday(&t, NULL); 352 ts.tv_sec = t.tv_sec; 353 ts.tv_nsec= t.tv_usec*1000; 354#endif // HAVE_POSIX_CLOCKS 355 ts.tv_sec += reltime/1000000000; 356 ts.tv_nsec+= reltime%1000000000; 357 if (ts.tv_nsec >= 1000000000) { 358 ts.tv_nsec -= 1000000000; 359 ts.tv_sec += 1; 360 } 361 return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts); 362#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE 363} 364inline void Condition::signal() { 365 pthread_cond_signal(&mCond); 366} 367inline void Condition::broadcast() { 368 pthread_cond_broadcast(&mCond); 369} 370 371#endif // HAVE_PTHREADS 372 373/*****************************************************************************/ 374 375/* 376 * This is our spiffy thread object! 377 */ 378 379class Thread : virtual public RefBase 380{ 381public: 382 // Create a Thread object, but doesn't create or start the associated 383 // thread. See the run() method. 384 Thread(bool canCallJava = true); 385 virtual ~Thread(); 386 387 // Start the thread in threadLoop() which needs to be implemented. 388 virtual status_t run( const char* name = 0, 389 int32_t priority = PRIORITY_DEFAULT, 390 size_t stack = 0); 391 392 // Ask this object's thread to exit. This function is asynchronous, when the 393 // function returns the thread might still be running. Of course, this 394 // function can be called from a different thread. 395 virtual void requestExit(); 396 397 // Good place to do one-time initializations 398 virtual status_t readyToRun(); 399 400 // Call requestExit() and wait until this object's thread exits. 401 // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call 402 // this function from this object's thread. Will return WOULD_BLOCK in 403 // that case. 404 status_t requestExitAndWait(); 405 406protected: 407 // exitPending() returns true if requestExit() has been called. 408 bool exitPending() const; 409 410private: 411 // Derived class must implement threadLoop(). The thread starts its life 412 // here. There are two ways of using the Thread object: 413 // 1) loop: if threadLoop() returns true, it will be called again if 414 // requestExit() wasn't called. 415 // 2) once: if threadLoop() returns false, the thread will exit upon return. 416 virtual bool threadLoop() = 0; 417 418private: 419 Thread& operator=(const Thread&); 420 static int _threadLoop(void* user); 421 const bool mCanCallJava; 422 thread_id_t mThread; 423 Mutex mLock; 424 Condition mThreadExitedCondition; 425 status_t mStatus; 426 volatile bool mExitPending; 427 volatile bool mRunning; 428 sp<Thread> mHoldSelf; 429#if HAVE_ANDROID_OS 430 int mTid; 431#endif 432}; 433 434 435}; // namespace android 436 437#endif // __cplusplus 438 439#endif // _LIBS_UTILS_THREADS_H 440