Corium 1.1.0
High-Performance Zero-Heap C++20 MPSC Application Runtime
Loading...
Searching...
No Matches
Semaphore.hpp
Go to the documentation of this file.
1
7#pragma once
8
9#include <atomic>
10#include <coroutine>
11#include <cstddef>
12
13namespace corium::async {
14
18public:
21 explicit constexpr AsyncSemaphore(ptrdiff_t initialCount = 1) noexcept
22 : m_count(initialCount)
23 {}
24
25 ~AsyncSemaphore() = default;
28
31 bool tryAcquire() noexcept {
32 ptrdiff_t current = m_count.load(std::memory_order_relaxed);
33 while (current > 0) {
34 if (m_count.compare_exchange_weak(current, current - 1,
35 std::memory_order_acquire,
36 std::memory_order_relaxed)) {
37 return true;
38 }
39 }
40 return false;
41 }
42
45 void release(ptrdiff_t update = 1) noexcept {
46 m_count.fetch_add(update, std::memory_order_release);
47 auto h = m_waiter.exchange(nullptr, std::memory_order_acq_rel);
48 if (h && !h.done()) {
49 h.resume();
50 }
51 }
52
54 [[nodiscard]] ptrdiff_t available() const noexcept {
55 return m_count.load(std::memory_order_relaxed);
56 }
57
61
62 [[nodiscard]] bool await_ready() const noexcept {
63 return sem.tryAcquire();
64 }
65
66 bool await_suspend(std::coroutine_handle<> h) noexcept {
67 if (sem.tryAcquire()) {
68 return false;
69 }
70 sem.m_waiter.store(h, std::memory_order_release);
71 return !sem.tryAcquire();
72 }
73
74 constexpr void await_resume() const noexcept {}
75 };
76
78 [[nodiscard]] AcquireAwaiter acquire() noexcept {
79 return AcquireAwaiter{*this};
80 }
81
82private:
83 std::atomic<ptrdiff_t> m_count{1};
84 std::atomic<std::coroutine_handle<>> m_waiter{nullptr};
85};
86
87} // namespace corium::async
Asynchronous counting semaphore for cooperative coroutine concurrency throttling.
Definition Semaphore.hpp:17
AsyncSemaphore & operator=(const AsyncSemaphore &)=delete
void release(ptrdiff_t update=1) noexcept
Release one or more permits and resume waiting coroutines.
Definition Semaphore.hpp:45
bool tryAcquire() noexcept
Non-blocking attempt to acquire a permit.
Definition Semaphore.hpp:31
AcquireAwaiter acquire() noexcept
Acquire a permit asynchronously (suspends coroutine until permit is released).
Definition Semaphore.hpp:78
constexpr AsyncSemaphore(ptrdiff_t initialCount=1) noexcept
Construct semaphore with initial available count.
Definition Semaphore.hpp:21
ptrdiff_t available() const noexcept
Available permit count.
Definition Semaphore.hpp:54
AsyncSemaphore(const AsyncSemaphore &)=delete
Definition AsyncEvent.hpp:14
Awaiter for acquiring a permit asynchronously.
Definition Semaphore.hpp:59
bool await_ready() const noexcept
Definition Semaphore.hpp:62
constexpr void await_resume() const noexcept
Definition Semaphore.hpp:74
AsyncSemaphore & sem
Definition Semaphore.hpp:60
bool await_suspend(std::coroutine_handle<> h) noexcept
Definition Semaphore.hpp:66