Async++ unknown
Async (co_await/co_return) code for C++
Loading...
Searching...
No Matches
latch.h
1#pragma once
2#include <asyncpp/event.h>
3#include <atomic>
4#include <cstddef>
5#include <limits>
6
7namespace asyncpp {
16 class latch {
17 public:
19 static constexpr std::size_t max = std::numeric_limits<std::size_t>::max();
20
25 explicit latch(std::size_t initial) noexcept : m_count{initial}, m_event{initial <= 0} {}
26
28 latch(const latch&) = delete;
29
31 latch& operator=(const latch&) = delete;
32
34 [[nodiscard]] bool is_ready() const noexcept { return m_event.is_set(); }
35
41 void decrement(std::size_t n = 1) noexcept {
42 if (m_count.fetch_sub(n, std::memory_order::acq_rel) == 0) { m_event.set(); }
43 }
44
48 [[nodiscard]] auto operator co_await() noexcept { return m_event.wait(dispatcher::current()); }
49
53 [[nodiscard]] auto wait(dispatcher* resume_dispatcher = nullptr) noexcept {
54 return m_event.wait(resume_dispatcher);
55 }
56
57 private:
58 std::atomic<std::size_t> m_count;
60 };
61} // namespace asyncpp
Basic dispatcher interface class.
Definition dispatcher.h:8
static dispatcher * current() noexcept
Definition dispatcher.h:48
The latch class is a downward counter of type std::size_t which can be used to synchronize coroutines...
Definition latch.h:16
static constexpr std::size_t max
The maximum value of counter supported.
Definition latch.h:19
void decrement(std::size_t n=1) noexcept
Decrement the latch counter.
Definition latch.h:41
latch(const latch &)=delete
latch is not copyable
bool is_ready() const noexcept
Check if the latch reached zero.
Definition latch.h:34
latch(std::size_t initial) noexcept
Constructs a latch and initializes its internal counter.
Definition latch.h:25
latch & operator=(const latch &)=delete
latch is not copyable
auto wait(dispatcher *resume_dispatcher=nullptr) noexcept
Wait for the counter to reach zero.
Definition latch.h:53
Simple manual reset event supporting multiple consumers.
Definition event.h:306
bool set(dispatcher *resume_dispatcher=nullptr) noexcept
Set the event.
Definition event.h:339
bool is_set() const noexcept
Query if the event is currently set.
Definition event.h:322
constexpr auto wait(dispatcher *resume_dispatcher=nullptr) noexcept
Suspend the current coroutine until the event is set.
Definition event.h:387