Linux多线程编程工具库liblmp_tool github: https://github.com/Dwyane05/liblmp_tool
CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有框架服务之后执行。
CountDownLatch原理
CountDownLatch是通过一个计数器来实现的,计数器的初始化值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就相应得减1。当计数器到达0时,表示所有的线程都已完成任务,然后在闭锁上等待的线程就可以恢复执行任务。
CountDownLatch原理示意图
CountDownLatch类实现:
头文件
/*
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* CountDownLatch.h
* Created on: May 30, 2019
* Author: cuiyongfei
*/
#ifndef LMP_TOOL_COUNTDOWNLATCH_H
#define LMP_TOOL_COUNTDOWNLATCH_H
#include "Condition.h"
#include "Mutex.h"
namespace lmp_tool
{
class CountDownLatch : noncopyable
{
public:
explicit CountDownLatch(int count);
void wait();
void countDown();
int getCount() const;
private:
mutable MutexLock mutex_;
Condition condition_ GUARDED_BY(mutex_);
int count_ GUARDED_BY(mutex_);
};
} // namespace lmp_tool
#endif // LMP_TOOL_COUNTDOWNLATCH_H
.cc实现:
/*
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* CountDownLatch.cc
* Created on: May 30, 2019
* Author: cuiyongfei
*/
#include "CountDownLatch.h"
using namespace lmp_tool;
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_;
}