为了方便开发,一般创建互斥量的管理类,同时创建上锁解锁类(RALL技术)
class MutexLock : boost::noncopyable { public: MutexLock() : holder_(0) //线程持有者 { MCHECK(pthread_mutex_init(&mutex_, NULL)); //mutex动态初始化 } ~MutexLock() { assert(holder_ == 0); //没有持有者 MCHECK(pthread_mutex_destroy(&mutex_)); //销毁mutex }
bool isLockedByThisThread() const //当上锁后才可调用 { return holder_ == CurrentThread::tid(); //判断持有者和当前线程是否相同 }
void lock() { MCHECK(pthread_mutex_lock(&mutex_)); //上锁 assignHolder(); //设置持有者 }
void unlock() { unassignHolder(); //清零持有者 MCHECK(pthread_mutex_unlock(&mutex_)); //解锁 }
pthread_mutex_t* getPthreadMutex() /* non-const */ { return &mutex_; //获得锁,由于条件变量有时候需要锁,因此返回其地址 }
private: friend class Condition; //友元类条件变量 //用于条件变量上锁后,执行wait操作时,解除线程绑定,防止其他线程上锁时调用失败 class UnassignGuard : boost::noncopyable
class MutexLockGuard : boost::noncopyable { public: explicit MutexLockGuard(MutexLock& mutex) : mutex_(mutex) { mutex_.lock(); //使用RALL技术,构造时获得资源,析构时释放资源 } ~MutexLockGuard() { mutex_.unlock(); }