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.spa
//自動互斥鎖。在函數頂部聲明其中一個,當函數返回時,它將超出範圍,並釋放對象
typedef Mutex::Autolock AutoMutex;it
Autolock是Mutex的內嵌類(Java叫內部類),io
// Manages the mutex automatically. It'll be locked when Autolock is
// constructed and released when Autolock goes out of scope.function
//自動管理互斥鎖。自動鎖定後它將被鎖定class
//在自動鎖定超出範圍時構建並釋放。thread
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;
};原理
看紅色部分的註釋就明白了,在函數代碼中使用 AutoMutex 就能夠鎖定對象,而代碼執行完AutoMutex所在的代碼域以後,就自動釋放鎖,它的原理是充分的利用了c++的構造和析構函數~