Muduo库源码分析(5):互斥锁,条件变量类

  1. 互斥锁(muduo库简单的封装)
    将muduo库的线程id的操作去除的简单版本
// 出错处理
#define MCHECK(ret) ({ __typeof__ (ret) errnum = (ret); assert(errnum == 0); (void) errnum;})
class MutexLock : noncopyable
{
 public:
  MutexLock()
  {
  // 初始化互斥锁
    MCHECK(pthread_mutex_init(&mutex_, NULL));
  }

  ~MutexLock()
  {
  // 销毁互斥锁
    MCHECK(pthread_mutex_destroy(&mutex_));
  }

  void lock()
  {
  // 加锁
    MCHECK(pthread_mutex_lock(&mutex_));
  }

  void unlock()
  {
  // 解锁
    MCHECK(pthread_mutex_unlock(&mutex_));
  }

  pthread_mutex_t* getPthreadMutex() 
  {
  // 获取锁
    return &mutex_;
  }

 private:
  pthread_mutex_t mutex_;// 互斥锁
};

// 对加锁和解锁操作进行封装,采用的是C++的RAII机制,好处是不需要手动进行解锁操作,由MutexLockGuard类自动管理解锁操作(析构函数完成)。
链接:[http://www.cnblogs.com/gnuhpc/archive/2012/12/04/2802307.html "C++ RAII机制"]
class MutexLockGuard : noncopyable
{
 public:
  explicit MutexLockGuard(MutexLock& mutex)
    : mutex_(mutex)
  {
    mutex_.lock();
  }

  ~MutexLockGuard()
  {
    mutex_.unlock();
  }
 private:
  MutexLock& mutex_;// 采用的是引用,目的是该类只负责加锁和解锁,而互斥量的销毁由MutexLock类负责 
};
// 阻止匿名互斥量的操作
#define MutexLockGuard(x) error "Missing guard object name"
  1. 条件变量类封装
 class Condition : noncopyable
{
 public:
  explicit Condition(MutexLock& mutex)
    : mutex_(mutex)
  {
  // 条件变量初始化
    MCHECK(pthread_cond_init(&pcond_, NULL));
  }

  ~Condition()
  {
  // 消除条件变量
    MCHECK(pthread_cond_destroy(&pcond_));
  }

  void wait()
  {
MCHECK(pthread_cond_wait(&pcond_,mutex_.getPthreadMutex()));
  }

 void notify()
  {
    MCHECK(pthread_cond_signal(&pcond_));
  }

  void notifyAll()
  {
    MCHECK(pthread_cond_broadcast(&pcond_));
  }
 bool waitForSeconds(double seconds)
 {
 struct timespec abstime;
  clock_gettime(CLOCK_REALTIME, &abstime);
  const int64_t kNanoSecondsPerSecond = 1e9;
  int64_t nanoseconds = static_cast(seconds * kNanoSecondsPerSecond);

  abstime.tv_sec += static_cast((abstime.tv_nsec + nanoseconds) / kNanoSecondsPerSecond);
  abstime.tv_nsec = static_cast<long>((abstime.tv_nsec + nanoseconds) % kNanoSecondsPerSecond);
  MutexLock::UnassignGuard ug(mutex_);
  return ETIMEDOUT == pthread_cond_timedwait(&pcond_, mutex_.getPthreadMutex(), &abstime);
 }

 private:
  MutexLock& mutex_;// 互斥量
  pthread_cond_t pcond_;// 条件变量
};
  1. CountDownLatch类:
    可实现子进程等待主进程发起命令后竞争执行
    (主线程调用countDown,子线程调用wait)
    也可实现主线程等待子进程初始化完成后在执行
    (主线程调用wait,子线程调用countDown)
class CountDownLatch : noncopyable
{
 public:

  explicit CountDownLatch(int count);

  void wait()
  {
   MutexLockGuard lock(mutex_); // 加锁
  while (count_ > 0)// 等待条件
  {
    condition_.wait();// 等待
  }
  }

  void countDown()
  {
   MutexLockGuard lock(mutex_);
  --count_;
  if (count_ == 0)
  {
    condition_.notifyAll();
  }
  }

  int getCount() const
  {
  MutexLockGuard lock(mutex_);
  return count_;
  }

 private:
  mutable MutexLock mutex_;// 声明为mutable的目的是因为getCount函数声明为const函数而该函数会改变锁的状态
  Condition condition_;
  int count_;
};

你可能感兴趣的:(Muduo,线程,muduo)