概述
CountDownLatch用线程同步的。
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"
namespace muduo
{
//对 Condition(条件变量)的封装,通过倒计时计数器的方式,设置计数
class CountDownLatch : noncopyable
{
public:
explicit CountDownLatch(int count); //count是线程的数量
void wait();
void countDown();
int getCount() const;
private: //CountDownLatch由一把锁,条件变量,计数器构成
mutable MutexLock mutex_;
Condition condition_ GUARDED_BY(mutex_);
int count_ GUARDED_BY(mutex_);//count是线程的数量
};
} // namespace muduo
#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)
{
}
void CountDownLatch::wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0) //只要计数值大于0,CountDownLatch类就不工作,知道等待计数值为0
{
condition_.wait();
}
}
void CountDownLatch::countDown() //倒数,倒计时
{
MutexLockGuard lock(mutex_);
--count_;
if (count_ == 0)
{
condition_.notifyAll();
}
}
int CountDownLatch::getCount() const //获得次数
{
MutexLockGuard lock(mutex_);
return count_;
}
最后
以上就是悲凉玫瑰为你收集整理的muduo之CountDownLatch.cc的全部内容,希望文章能够帮你解决muduo之CountDownLatch.cc所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复