Android中的AutoMutex
在Threads.h文件中定义:
1 /* 2 * Automatic mutex. Declare one of these at the top of a function. 3 * When the function returns, it will go out of scope, and release the 4 * mutex. 5 */ 6 7 typedef Mutex::Autolock AutoMutex;
其中的Autolock:
1 // Manages the mutex automatically. It'll be locked when Autolock is 2 // constructed and released when Autolock goes out of scope. 3 class Autolock { 4 public: 5 inline Autolock(Mutex& mutex) : mLock(mutex) { mLock.lock(); } 6 inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); } 7 inline ~Autolock() { mLock.unlock(); } 8 private: 9 Mutex& mLock; 10 };
看看AutoMutex的用法:
1、
1 int32_t Asset::getGlobalCount() 2 { 3 AutoMutex _l(gAssetLock); 4 return gCount; 5 }
2、
1 ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res) 2 { 3 { 4 AutoMutex _l(gLock); 5 if (mResourceTable == NULL) { 6 mResourceTable = res; 7 return res; 8 } 9 } 10 delete res; 11 return mResourceTable; 12 }
我认为特别是第二种用法,完全是对变量存在域的一种精辟理解。学习了。