-
Notifications
You must be signed in to change notification settings - Fork 1
/
MCRingBuffer7.hpp
54 lines (48 loc) · 1.7 KB
/
MCRingBuffer7.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
42
43
44
45
46
47
48
49
50
51
52
53
#pragma once
#include <atomic>
#include <array>
#include <cstddef>
#include <new>
#include <type_traits>
template<typename T, std::size_t SIZE>
struct MCRingBuffer7 {
using value_type = T;
alignas(128) std::array<std::byte, sizeof(T) * SIZE> buffer;
alignas(128) std::atomic<T*> tail;
mutable T* head_cache;
alignas(128) std::atomic<T*> head;
mutable T* tail_cache;
MCRingBuffer7() :
tail(reinterpret_cast<T*>(buffer.data())),
head_cache(reinterpret_cast<T*>(buffer.data())),
head(reinterpret_cast<T*>(buffer.data())),
tail_cache(reinterpret_cast<T*>(buffer.data())) {}
template<typename... Args>
int Enqueue(Args&&... args) {
T* t = tail.load(std::memory_order_relaxed);
T* n = (t + 1);
if (n == reinterpret_cast<T*>(buffer.data() + buffer.max_size()))
n = reinterpret_cast<T*>(buffer.data());
T* h = head_cache;
if (n == h && n == (head_cache = head.load(std::memory_order_acquire)))
return 0;
new(t) T(std::forward<Args>(args)...);
tail.store(n, std::memory_order_release);
return 1;
}
template<typename Callable>
int Dequeue(Callable&& f) {
T* h = head.load(std::memory_order_relaxed);
T* t = tail_cache;
if (h == t && h == (tail_cache = tail.load(std::memory_order_acquire)))
return 0;
T* elem = std::launder(h);
std::invoke(std::forward<Callable>(f), std::move(*elem));
elem->~T();
h += 1;
if (h == reinterpret_cast<T*>(buffer.data() + buffer.max_size()))
h = reinterpret_cast<T*>(buffer.data());
head.store(h, std::memory_order_release);
return 1;
}
};