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

相關文章
相關標籤/搜索