//Mutex.h
class MutexLock : noncopyable
{
public:
MutexLock()
: holder_(0)
{
MCHECK(pthread_mutex_init(&mutex_, NULL));
}
~MutexLock()
{
assert(holder_ == 0);
MCHECK(pthread_mutex_destroy(&mutex_));
}
// must be called when locked, i.e. for assertion
bool isLockedByThisThread() const
{
return holder_ == CurrentThread::tid();
}
void assertLocked() const
{
assert(isLockedByThisThread());
}
void lock()
{
MCHECK(pthread_mutex_lock(&mutex_));
holder_ = CurrentThread::tid();
}
void unlock()
{
holder_ = 0;
MCHECK(pthread_mutex_unlock(&mutex_));
}
pthread_mutex_t* getPthreadMutex() /* non-const */
{
return &mutex_;
}
private:
pthread_mutex_t mutex_;
pid_t holder_;
- MutexLock提供加锁、解锁;获取对当前锁加锁的线程tid。
//Mutex.h
class MutexLockGuard : noncopyable
{
public:
explicit MutexLockGuard(MutexLock& mutex)
: mutex_(mutex)
{
mutex_.lock();
}
~MutexLockGuard()
{
mutex_.unlock();
}
private:
MutexLock& mutex_; //此处为引用,说明此类不控制mutex锁的生存周期
};
//不允许使用匿名锁
#define MutexLockGuard(x) error "Missing guard object name"
- 封装锁,在构造函数中加锁,在析构函数中解锁(临界区结束,销毁局部变量-MutexLockGuard对象,调用析构,解锁),减少了死锁风险;否则如果在解锁前退出临界区,会造成死锁。
- 例:
Mutex mutex;
mutex.lock();
//MutexLockGuard m(mutex);
…
if(…){
…
return;//未解锁
}
muetx.unlock();
这种情况下,未解锁就返回,造成死锁。若使用MutexLockGuard,则在返回时调用析构,解锁。