本文主要是介绍Android中线程同步之MUTEX与Condtion的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
田海立2013-08-10
Android封装的同步类主要有MUTEX(AutoMutex)与Condition。前文分析了它们的外部使用,本文看它们是如何通过对pthread Mutex和Condition的封装实现的。遇到pthread的用法,可结合《 pthread之MUTEX与Condition用法》一起看。
Keywords: Mutex, Condition Variable, AutoLock/AutoMutex, Android
关键字:互斥体、条件变量、自动锁/自动互斥体、Android
一、MUTEX的实现
MUTEX的实现是在frameworks/native/include/utils/Mutex.h中。
Mutex的实现利用了pthread Mutex的实现。
首先,Class Mutex内部定义一个pthread_mutex
pthread_mutex_t mMutex;
然后,分别封装了pthread_mutex_xxx()而已:
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) {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);}
}
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);
}
具体pthread Mutex的用法,参见《pthread之MUTEX与Condition用法》
二、Autolock/AutoMutex的实现
Autolock/AutoMutex的实现同样是在frameworks/native/include/utils/Mutex.h中。namespace android {class Mutex {//...class Autolock {public:inline Autolock(Mutex& mutex) : mLock(mutex) { mLock.lock(); }inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }inline ~Autolock() { mLock.unlock(); }private:Mutex& mLock;};}; // end of class Mutextypedef Mutex::Autolock AutoMutex;}; // namespace android
三、Condition的实现
Condition的实现是在frameworks/native/include/utils/Condition.h中Condition的实现利用了pthread Condition的实现。
首先,Class Condition内定义一个pthread_cond
pthread_cond_t mCond;
然后,分别封装了pthread_cond_xxx()而已:
inline Condition::Condition() {pthread_cond_init(&mCond, NULL);
}
inline Condition::Condition(int type) {if (type == SHARED) {pthread_condattr_t attr;pthread_condattr_init(&attr);pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);pthread_cond_init(&mCond, &attr);pthread_condattr_destroy(&attr);} else {pthread_cond_init(&mCond, NULL);}
}
inline Condition::~Condition() {pthread_cond_destroy(&mCond);
}
inline status_t Condition::wait(Mutex& mutex) {return -pthread_cond_wait(&mCond, &mutex.mMutex);
}
inline void Condition::signal() {pthread_cond_signal(&mCond);
}
inline void Condition::broadcast() {pthread_cond_broadcast(&mCond);
}
具体pthread Condition的用法,参见《pthread之MUTEX与Condition用法》
四、总结
本文简要介绍了Android中常用的同步机制Mutex(AutoMutex)、Condition的内部实现,也就是对pthread Mutex和Condition的简单封装。《 pthread之MUTEX与Condition用法》中介绍pthread中Mutex与Condition的用法。这篇关于Android中线程同步之MUTEX与Condtion的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!