简介
CountDownLatch称为门阀,用于等待另外线程执行完成
结构
内部使用count_
来计数,表示需要等待的线程数,线程执行完后减1,等待线程等待直到计数为0
构造函数
初始化互斥量,条件变量,以及需要等待的线程数
CountDownLatch::CountDownLatch(int count): mutex_(),condition_(mutex_),count_(count)
{
}
wait
等待线程执行完
void CountDownLatch::wait()
{MutexLockGuard lock(mutex_);while (count_ > 0){condition_.wait();}
}
countDown
线程执行完后,调用countDown
将计数减1,当减到0时,会唤醒等待线程
void CountDownLatch::countDown()
{MutexLockGuard lock(mutex_);--count_;if (count_ == 0){condition_.notifyAll();}
}
getCount
获取等待的线程数
int CountDownLatch::getCount() const
{MutexLockGuard lock(mutex_);return count_;
}