我看到一个头文件如下:
#include <pthread.h>
#define lock(x) if(Lock _lock_=x){}else
class Mutex{
public:
Mutex(){
pthread_mutex_init(&mutex_, 0);
};
~Mutex(){
pthread_mutex_destroy(&mutex_);
};
friend class Lock;
private:
pthread_mutex_t mutex_;
void Lock(){
pthread_mutex_lock(&mutex_);
};
void Unlock(){
pthread_mutex_unlock(&mutex_);
};
};
class Lock{
public:
Lock(Mutex& mutex):mutex_(mutex){mutex_.Lock();};
~Lock(){mutex_.Unlock();};
operator bool() const {
return false;
}
private:
Mutex& mutex_;
};
它定义了一个lock(x)
宏。下面是如何使用这个宏:
...
Mutex mtx;
lock(mtx) {
// critical section
}
...
那么,这个锁宏是如何工作的呢?为什么?