Linux多線程C++工具庫:liblmp_tool -- 同步工具CountDownLatch

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_;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章