☎️ rtchan
Realtime-safe channels (lock-free queues) for C++20
Loading...
Searching...
No Matches
spmc.hpp
1/*
2 * rtchan - Realtime-safe channels via lock-free ringbuffer queues
3 * Copyright (c) 2025 Fawn <rubiefawn@gmail.com>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18#pragma once
19#include "rtchan.hpp"
20#include "internal/busy_wait_hint.h"
21#include <array>
22#include <bit> // std::has_single_bit() to ensure the buffer length is a power of 2
23
24namespace rtchan {
25
29template<typename T, size_t N>
30requires (0 < N) && (std::has_single_bit(N))
31class spmc : public chan<T> {
32private:
33 static constexpr auto index_wrapped(size_t index) noexcept -> size_t { return index & (N - 1); };
34 std::array<T, N> buf = {};
35 alignas(std::hardware_destructive_interference_size) std::atomic_size_t read_committed = 0;
36 alignas(std::hardware_destructive_interference_size) std::atomic_size_t read_claimed = 0;
37 alignas(std::hardware_destructive_interference_size) std::atomic_size_t write_index = 0;
38};
39
40} // namespace rtchan
Abstract common interface for all queues.
Definition rtchan.hpp:52
Single-producer, multiple-consumer queue.
Definition spmc.hpp:31