muduo/base库学习笔记(4)-----MutexLock类

MutexLock类
muduo/base库学习笔记(4)-----MutexLock类_第1张图片

1 构造函数和析构函数的实现

构造函数的实现

 MutexLock()
    : holder_(0)
  {
  //进行加锁
    MCHECK(pthread_mutex_init(&mutex_, NULL));
  }

析构函数的实现

 ~MutexLock()
  {
    assert(holder_ == 0);
    //解锁
    MCHECK(pthread_mutex_destroy(&mutex_));
  }

2 普通成员函数的实现

isLockedByThisThread()函数的实现

 bool isLockedByThisThread() const
  {
    return holder_ == CurrentThread::tid();
  }

assertLocked()函数的实现

void assertLocked() const ASSERT_CAPABILITY(this)
  {
    assert(isLockedByThisThread());
  }


** lock()函数的实现**

 void lock() ACQUIRE()
  {
    MCHECK(pthread_mutex_lock(&mutex_));
    assignHolder();
  }

unlock()函数的实现

void unlock() RELEASE()
  {
    unassignHolder();
    MCHECK(pthread_mutex_unlock(&mutex_));
  }

获取当前锁getPthreadMutex()

pthread_mutex_t* getPthreadMutex() /* non-const */
  {
    return &mutex_;
  }


初始化锁的拥有者

 class UnassignGuard : noncopyable
  {
   public:
    explicit UnassignGuard(MutexLock& owner)
      : owner_(owner)
    {
      owner_.unassignHolder();
    }

    ~UnassignGuard()
    {
      owner_.assignHolder();
    }

   private:
    MutexLock& owner_;
  };

  void unassignHolder()
  {
    holder_ = 0;
  }

  void assignHolder()
  {
    holder_ = CurrentThread::tid();
  }

3 一个专门对MutexLock进行管理的类

该类在构造函数中加锁
在析构函数中解锁

 explicit MutexLockGuard(MutexLock& mutex) ACQUIRE(mutex)
    : mutex_(mutex)
  {
    mutex_.lock();
  }

  ~MutexLockGuard() RELEASE()
  {
    mutex_.unlock();
  }

 private:

  MutexLock& mutex_;
};

这儿有一个错误提示,匿名对象不能长时间的拥有一把锁

#define MutexLockGuard(x) error "Missing guard object name"

#endif  // MUDUO_BASE_MUTEX_H
                              

你可能感兴趣的:(muduo)