#pragma once #include #include #include namespace Void::Async { // ── MpscQueue ────────────────────────────────────────────────────────────── // Unbounded multi-producer / single-consumer queue (Vyukov scheme). // // push() — any thread; wait-free (one exchange + one store, no CAS loop). // try_pop() — exactly ONE consumer thread; lock-free. // // Memory reclamation is trivial by construction: only the consumer ever // dereferences and frees popped nodes, so there are no hazard pointers, no // epochs, and no ABA window (no compare-and-swap on shared nodes at all). // // Known Vyukov subtlety: a producer can be preempted between swapping the // tail and linking the previous node's `next`. During that window the chain // is transiently broken and try_pop() reports the queue as empty even though // later-pushed items exist. Callers must treat empty() / nullopt as a hint // and re-poll; items are never lost. // // The queue carries no blocking facility by design — consumers that need to // sleep when idle pair it with a std::binary_semaphore (see ManualExecutor // and the Fsm worker for the pattern). template class MpscQueue { public: MpscQueue() : head_{new Node{}}, tail_{head_} {} MpscQueue(const MpscQueue&) = delete; MpscQueue& operator=(const MpscQueue&) = delete; MpscQueue(MpscQueue&&) = delete; MpscQueue& operator=(MpscQueue&&) = delete; ~MpscQueue() { // No concurrent access is permitted during destruction. Node* n = head_; while (n) { Node* next = n->next.load(std::memory_order_relaxed); delete n; n = next; } } // Enqueue from any thread. Wait-free. void push(T value) { Node* node = new Node{std::move(value)}; Node* prev = tail_.exchange(node, std::memory_order_acq_rel); // A consumer scanning right now sees prev->next == nullptr and // treats the queue as empty until this store lands (see above). prev->next.store(node, std::memory_order_release); } // Dequeue. Must only ever be called from one consumer thread. // Returns nullopt when the queue is empty *or* a producer is mid-link. [[nodiscard]] std::optional try_pop() { Node* head = head_; Node* next = head->next.load(std::memory_order_acquire); if (!next) { return std::nullopt; } std::optional result{std::move(*next->value)}; next->value.reset(); head_ = next; delete head; return result; } // Consumer-side emptiness hint; racy when observed from other threads. [[nodiscard]] bool empty() const noexcept { return head_->next.load(std::memory_order_acquire) == nullptr; } private: struct Node { Node() = default; explicit Node(T v) : value{std::move(v)} {} std::atomic next{nullptr}; std::optional value{}; // disengaged only in the stub node }; Node* head_; // consumer-owned; always the consumed stub std::atomic tail_; // producers swap themselves in here }; } // namespace Void::Async