count_down_latch.h 784 B

1234567891011121314151617181920212223242526272829303132333435
  1. //
  2. // Created by devyk on 2021/10/14.
  3. //
  4. #ifndef BITSTREAMANALYZE_COUNT_DOWN_LATCH_H
  5. #define BITSTREAMANALYZE_COUNT_DOWN_LATCH_H
  6. #include <mutex>
  7. #include <condition_variable>
  8. class CountDownLatch {
  9. public:
  10. CountDownLatch(uint32_t count) : m_count(count) {}
  11. void countDown() noexcept {
  12. std::lock_guard<std::mutex> guard(m_mutex);
  13. if (0 == m_count) {
  14. return;
  15. }
  16. --m_count;
  17. if (0 == m_count) {
  18. m_cv.notify_all();
  19. }
  20. }
  21. void await() noexcept {
  22. std::unique_lock<std::mutex> lock(m_mutex);
  23. m_cv.wait(lock, [this] { return 0 == m_count; });
  24. }
  25. private:
  26. std::mutex m_mutex;
  27. std::condition_variable m_cv;
  28. uint32_t m_count;
  29. };
  30. #endif //BITSTREAMANALYZE_COUNT_DOWN_LATCH_H