-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRingBuffer.hpp
More file actions
56 lines (44 loc) · 1.26 KB
/
RingBuffer.hpp
File metadata and controls
56 lines (44 loc) · 1.26 KB
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
54
55
56
#ifndef RINGBUFFER_HPP
#define RINGBUFFER_HPP
#include <atomic>
#include <cstddef>
template<typename T, size_t Size>
class RingBuffer{
private:
std::atomic<size_t> head;
std::atomic<size_t> tail;
T buffer[Size];
public:
RingBuffer(){
head.store(0); // READ (DEQUEUE)
tail.store(0); // WRITE (ENQUE)
}
bool push(T item){
size_t t= tail.load(std::memory_order_relaxed);
size_t h= head.load(std::memory_order_acquire);
if(((t+1)% Size)==h){
return false; // FULL
}
buffer[t]= item;
tail.store((t+1)%Size, std::memory_order_release);
return true;
}
bool pop(T &item){
size_t h= head.load(std::memory_order_relaxed);
size_t t= tail.load(std::memory_order_acquire);
if(h==t) return false; // EMPTY
item= buffer[h];
head.store((h+1)%Size, std::memory_order_release);
return true;
}
bool empty(){
return head.load(std::memory_order_relaxed) == tail.load(std::memory_order_relaxed);
}
bool full(){
return ((tail.load(std::memory_order_relaxed)+1)%Size)==head.load(std::memory_order_relaxed);
}
size_t capacity(){
return Size;
}
};
#endif // RINGBUFFER_HPP