首页 > 代码库 > android分析之mutex

android分析之mutex

 

Android的锁是对Linux锁的一种包装:

// ---------------------------------------------------------------------------namespace android {// ---------------------------------------------------------------------------class Condition;/* * Simple mutex class.  The implementation is system-dependent. * * The mutex must be unlocked by the thread that locked it.  They are not * recursive, i.e. the same thread can‘t lock it multiple times. */class Mutex {public:    enum {        PRIVATE = 0,//该锁为本进程内使用        SHARED = 1//该锁跨进程使用    };                    Mutex();                Mutex(const char* name);                Mutex(int type, const char* name = NULL);                ~Mutex();    // lock or unlock the mutex    status_t    lock();    void        unlock();    // lock if possible; returns 0 on success, error otherwise    status_t    tryLock();    // Manages the mutex automatically. It‘ll be locked when Autolock is    // constructed and released when Autolock goes out of scope.    class Autolock {//内部类,用来管理mutex的--相当于“智能指针”    public:        inline Autolock(Mutex& mutex) : mLock(mutex)  { mLock.lock(); }        inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }        inline ~Autolock() { mLock.unlock(); }    private:        Mutex& mLock;//持有mutex的引用    };private:    friend class Condition;//友元类,Condition是在mutex的基础上使用的        // A mutex cannot be copied                Mutex(const Mutex&);//设为私有,无法调用“拷贝构造函数”    Mutex&      operator = (const Mutex&);    #if defined(HAVE_PTHREADS)    pthread_mutex_t mMutex;//使用linux的pthread_mutex_t这个互斥锁#else    void    _init();    void*   mState;#endif};// ---------------------------------------------------------------------------#if defined(HAVE_PTHREADS)inline Mutex::Mutex() {    pthread_mutex_init(&mMutex, NULL);}inline Mutex::Mutex(const char* name) {    pthread_mutex_init(&mMutex, NULL);}inline Mutex::Mutex(int type, const char* name) {    if (type == SHARED) {//if分支:根据传进来的值,决定是否构造“跨进程”的锁        pthread_mutexattr_t attr;        pthread_mutexattr_init(&attr);        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);        pthread_mutex_init(&mMutex, &attr);        pthread_mutexattr_destroy(&attr);    } else {        pthread_mutex_init(&mMutex, NULL);//if分支:本进程内的锁    }}inline Mutex::~Mutex() {    pthread_mutex_destroy(&mMutex);}inline status_t Mutex::lock() {    return -pthread_mutex_lock(&mMutex);}inline void Mutex::unlock() {    pthread_mutex_unlock(&mMutex);}inline status_t Mutex::tryLock() {    return -pthread_mutex_trylock(&mMutex);}#endif // HAVE_PTHREADS// ---------------------------------------------------------------------------/* * Automatic mutex.  Declare one of these at the top of a function. * When the function returns, it will go out of scope, and release the * mutex. */ typedef Mutex::Autolock AutoMutex;// ---------------------------------------------------------------------------}; // namespace android  

  

android分析之mutex