-
Notifications
You must be signed in to change notification settings - Fork 1
/
MCRingBuffer1.hpp
42 lines (37 loc) · 1.15 KB
/
MCRingBuffer1.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#pragma once
#include <atomic>
#include <array>
#include <cstddef>
#include <new>
#include <type_traits>
template<typename T, std::size_t SIZE>
struct MCRingBuffer1 {
using value_type = T;
alignas(64) std::atomic_size_t tail{ 0 };
mutable size_t head_cache{ 0 };
alignas(64) std::atomic_size_t head{ 0 };
mutable size_t tail_cache{ 0 };
alignas(64) std::array<std::byte, sizeof(T) * SIZE> buffer;
template<typename... Args>
int Enqueue(Args&&... args) {
size_t t = tail;
size_t n = (t + 1) % SIZE;
size_t h = head_cache;
if (n == h && n == (head_cache = head)) return 0;
new(buffer.data() + t * sizeof(T)) T(std::forward<Args>(args)...);
tail = n;
return 1;
}
template<typename Callable>
int Dequeue(Callable&& f) {
size_t h = head;
size_t t = tail_cache;
if (h == t && h == (tail_cache = tail)) return 0;
T* elem = std::launder(reinterpret_cast<T*>(
buffer.data() + h * sizeof(T)));
std::invoke(std::forward<Callable>(f), std::move(*elem));
elem->~T();
head = (h + 1) % SIZE;
return 1;
}
};