-
Notifications
You must be signed in to change notification settings - Fork 1
/
LamportQueue6.hpp
43 lines (38 loc) · 1.27 KB
/
LamportQueue6.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
#pragma once
#include <atomic>
#include <array>
#include <cstddef>
#include <new>
#include <type_traits>
template<typename T, std::size_t SIZE>
struct alignas(64) LamportQueue6 {
using value_type = T;
alignas(64) std::atomic_size_t tail{ 0 };
alignas(64) std::atomic_size_t head{ 0 };
alignas(64) 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);
if (n == SIZE) n = 0;
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 += 1;
if (h == SIZE) h = 0;
head.store(h, std::memory_order_release);
return 1;
}
};