#ifndef MUDUO_BASE_COUNTDOWNLATCH_H
#define MUDUO_BASE_COUNTDOWNLATCH_H
#include "./Condition.h"
#include "./Mutex.h"
#include <boost/noncopyable.hpp>
namespace muduo
{
class CountDownLatch : boost::noncopyable//CountDownLatch作为成员的计数器使用
{
public:
explicit CountDownLatch(int count);
void wait();
void countDown();
int getCount() const;
private:
mutable MutexLock mutex_;
Condition condition_;
int count_;
};
}
#endif // MUDUO_BASE_COUNTDOWNLATCH_H
#include "./CountDownLatch.h"
using namespace muduo;
CountDownLatch::CountDownLatch(int count)
: mutex_(),
condition_(mutex_),
count_(count)
{
}
void CountDownLatch::wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0)
{
condition_.wait();
}
}
void CountDownLatch::countDown()
{
MutexLockGuard lock(mutex_);
--count_;
if (count_ == 0)//一旦目标线程全部开启,发送信号使等待中的线程解锁
{
condition_.notifyAll();
}
}
int CountDownLatch::getCount() const
{
MutexLockGuard lock(mutex_);
return count_;
}