forked from unhuman-io/motorlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcstack.h
46 lines (42 loc) · 1.07 KB
/
cstack.h
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
#ifndef UNHUMAN_MOTORLIB_CSTACK_H_
#define UNHUMAN_MOTORLIB_CSTACK_H_
#include <atomic>
// A circular stack. If data is written by one thread and read by one other thread then data is read from the top without worrying about thread safety.
template <class T, int size=100>
class CStack {
public:
CStack() = default;
void copy(const CStack &stack) {
pos_ = stack.pos_.load(std::memory_order_acquire);
for(int i=0;i<size;i++) {
data_[pos_] = stack.data_[pos_];
pos_++;
if (pos_ >= size) {
pos_ = 0;
}
}
future_pos_ = stack.future_pos_;
}
void push(T const &t) {
next() = t;
finish();
}
T &next() {
future_pos_ = pos_.load(std::memory_order_acquire) + 1;
if (future_pos_ >= size) {
future_pos_ = 0;
}
return data_[future_pos_];
}
void finish() {
pos_.store(future_pos_, std::memory_order_release);
}
const T &top() const { // return a copy of the data
return data_[pos_.load(std::memory_order_acquire)];
}
private:
T data_[size] = {};
std::atomic<int> pos_ = {0};
int future_pos_ = {0};
};
#endif // UNHUMAN_MOTORLIB_CSTACK_H_