“倒计时门闩”同步
实现:CountDownLatch类
功能:利用条件变量、倒计时实现同步
知识点:
- mutable:mutable修饰符表示其可以在任何情况下变化
- 条件变量
- 互斥锁
用途:
用于实现倒计时同步
代码及分析:
CountDownLatch.h
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#ifndef MUDUO_BASE_COUNTDOWNLATCH_H
#define MUDUO_BASE_COUNTDOWNLATCH_H
#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>
#include <boost/noncopyable.hpp>
namespace muduo
{
class CountDownLatch : boost::noncopyable
{
public:
//构造函数,初始化倒计时变量
explicit CountDownLatch(int count);
//等待count_为0
void wait();
//变量减一
void countDown();
//返回变量值
int getCount() const;
private:
mutable MutexLock mutex_;//互斥锁,mutable修饰符表示其可以在任何情况下变化
Condition condition_;//条件变量
int count_; //计时数
};
}
#endif // MUDUO_BASE_COUNTDOWNLATCH_H
CountDownLatch.cc
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include <muduo/base/CountDownLatch.h>
using namespace muduo;
//析构函数,对其进行初始化
CountDownLatch::CountDownLatch(int count)
: mutex_(),
condition_(mutex_),
count_(count)
{
}
//等待变量到0
void CountDownLatch::wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0)
{
condition_.wait();
}
}
//对变量减一,如果其为0,则唤醒等待的进程
void CountDownLatch::countDown()
{
MutexLockGuard lock(mutex_);
--count_;
if (count_ == 0)
{
condition_.notifyAll();
}
}
//返回计数递减变量值
int CountDownLatch::getCount() const
{
MutexLockGuard lock(mutex_);
return count_;
}