您的位置:首页 > 理论基础 > 计算机网络

[Muduo网络库源码分析] (3) base/CountDownLatch.cc_h_“倒计时门闩”同步

2017-07-31 09:10 639 查看

“倒计时门闩”同步

实现: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_;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: