-
Notifications
You must be signed in to change notification settings - Fork 1
/
LamportQueue8.hpp
41 lines (36 loc) · 1.23 KB
/
LamportQueue8.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
#pragma once
#include <atomic>
#include <array>
#include <cstddef>
#include <new>
#include <type_traits>
template<typename T, std::size_t SIZE>
struct alignas(128) LamportQueue8 {
using value_type = T;
alignas(128) std::atomic_size_t tail{ 0 };
alignas(128) std::atomic_size_t head{ 0 };
alignas(128) std::array<std::byte, sizeof(T) * SIZE> buffer;
template<typename... Args>
int Enqueue(Args&&... args) {
size_t t = tail.load(std::memory_order_relaxed);
size_t n = (t + 1) % SIZE;
size_t h = head.load(std::memory_order_acquire);
if (h == n) return 0;
new(buffer.data() + t * sizeof(T)) T(std::forward<Args>(args)...);
tail.store(n, std::memory_order_release);
return 1;
}
template<typename Callable>
int Dequeue(Callable&& f) {
size_t h = head.load(std::memory_order_relaxed);
size_t t = tail.load(std::memory_order_acquire);
if (h == t) 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();
h = (h + 1) % SIZE;
head.store(h, std::memory_order_release);
return 1;
}
};