源码
CountDownLatch.h
#pragma once
#include "Mutex.h"
#include "Condition.h"
#include "NonCopyable.h"
namespace muduo
{
class CountDownLatch : public NonCopyable
{
public:
explicit CountDownLatch(int count);
void wait();
void count_down();
int get_count() const;
private:
mutable MutexLock mutex_;
int count_;
Condition condition_;
};
} // namespace muduo
CountDownLatch.cc
#include "CountDownLatch.h"
namespace muduo
{
CountDownLatch::CountDownLatch(int count) : mutex_(), count_(count), condition_(mutex_)
{
}
void CountDownLatch::wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0)
{
condition_.wait();
}
}
void CountDownLatch::count_down()
{
MutexLockGuard lock(mutex_);
--count_;
if (count_ == 0)
{
condition_.notify_all();
}
}
int CountDownLatch::get_count() const
{
MutexLockGuard lock(mutex_);
return count_;
}
}