我是靠谱客的博主 悲凉玫瑰,最近开发中收集的这篇文章主要介绍muduo之CountDownLatch.cc,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

        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所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部