muduo之CountDownLatch.cc
生活随笔
收集整理的這篇文章主要介紹了
muduo之CountDownLatch.cc
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ??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 { //對(duì) Condition(條件變量)的封裝,通過倒計(jì)時(shí)計(jì)數(shù)器的方式,設(shè)置計(jì)數(shù) class CountDownLatch : noncopyable {public:explicit CountDownLatch(int count); //count是線程的數(shù)量void wait();void countDown();int getCount() const;private: //CountDownLatch由一把鎖,條件變量,計(jì)數(shù)器構(gòu)成mutable MutexLock mutex_;Condition condition_ GUARDED_BY(mutex_);int count_ GUARDED_BY(mutex_);//count是線程的數(shù)量 };} // namespace muduo #endif // MUDUO_BASE_COUNTDOWNLATCH_HCountDownLatch.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)//倒計(jì)時(shí)計(jì)數(shù)器: mutex_(),condition_(mutex_), //初始化,條件變量用成員鎖初始化count_(count) { }void CountDownLatch::wait() {MutexLockGuard lock(mutex_);while (count_ > 0) //只要計(jì)數(shù)值大于0,CountDownLatch類就不工作,知道等待計(jì)數(shù)值為0{condition_.wait();} }void CountDownLatch::countDown() //倒數(shù),倒計(jì)時(shí) {MutexLockGuard lock(mutex_);--count_;if (count_ == 0){condition_.notifyAll();} }int CountDownLatch::getCount() const //獲得次數(shù) {MutexLockGuard lock(mutex_);return count_; }?
總結(jié)
以上是生活随笔為你收集整理的muduo之CountDownLatch.cc的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: muduo之ThreadPool
- 下一篇: muduo之Singleton