roo_threads
API Documentation for roo_threads
Loading...
Searching...
No Matches
latch.h
Go to the documentation of this file.
1#pragma once
2
4#include "roo_threads/mutex.h"
5
6namespace roo {
7
8/// @brief A synchronization aid that blocks until a counter reaches zero.
9class latch {
10 public:
11 /// @brief Creates a latch with an initial counter value.
12 /// @param count initial counter value.
13 explicit latch(std::ptrdiff_t count) : count_(count) {}
14
15 /// @brief Decrements the counter and wakes waiters when it reaches zero.
16 /// @param n decrement amount.
17 void count_down(std::ptrdiff_t n = 1) {
18 roo::lock_guard<roo::mutex> lock(mutex_);
19 if ((count_ -= n) == 0) {
20 cv_.notify_all(); // Wake ALL waiters
21 }
22 }
23
24 /// @brief Blocks until the internal counter reaches zero.
25 void wait() const {
26 roo::unique_lock<roo::mutex> lock(mutex_);
27 cv_.wait(lock, [this] { return count_ == 0; });
28 }
29
30 private:
31 mutable roo::mutex mutex_;
32 mutable roo::condition_variable cv_;
33 std::ptrdiff_t count_;
34};
35
36} // namespace roo
A synchronization aid that blocks until a counter reaches zero.
Definition latch.h:9
void wait() const
Blocks until the internal counter reaches zero.
Definition latch.h:25
latch(std::ptrdiff_t count)
Creates a latch with an initial counter value.
Definition latch.h:13
void count_down(std::ptrdiff_t n=1)
Decrements the counter and wakes waiters when it reaches zero.
Definition latch.h:17
Definition latch.h:6