muduo之CountDownLatch.cc
生活随笔
收集整理的這篇文章主要介紹了
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_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)//倒計時計數器: 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之ThreadPool
- 下一篇: muduo之Singleton