AutoMutex

Android里的C++代码常常会看到AutoMutex _l(mLock); c++

AutoMutex其实就是Thread的一种自动的互斥锁,定义在framework/base/include/utils/thread.h中; 函数

/* 
* 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; spa

 

Autolock是Mutex的内嵌类(Java叫内部类), 对象

// Manages the mutex automatically. It'll be locked when Autolock is 
// constructed and released when Autolock goes out of scope. 
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; 
}; it

 

看红色部分的注释就明白了,在函数代码中使用 AutoMutex 就能够锁定对象,而代码执行完AutoMutex所在的代码域以后,就自动释放锁,它的原理是充分的利用了c++的构造和析构函数~ io

相关文章
相关标签/搜索