Android里的C++代码经常会看到AutoMutex _l(mLock);
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;
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; };
看红色部分的注释就明白了,在函数代码中使用 AutoMutex 就可以锁定对象,而代码执行完AutoMutex所在的代码域之后,就自动释放锁,它的原理是充分的利用了c++的构造和析构函数~