-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_test.cpp
More file actions
142 lines (122 loc) · 2.55 KB
/
queue_test.cpp
File metadata and controls
142 lines (122 loc) · 2.55 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <stdio.h>
#include <vector>
#include <mutex>
// template <typename T>
// struct laxatomic : std::atomic<T>()
// {
// void store( T desired) noexcept
// {
// }
// };
#define ROOM 4
template <typename Type, unsigned int Size>
struct queue
{
struct entry
{
Type Data;
int Gen;
};
struct geni
{
int val, Gen;
void incr()
{
if (++val % Size == 0)
{
val = 0;
Gen++;
}
}
operator int()
{
return val;
}
//operator<() = default;
};
std::atomic<entry> Buffer[Size];
std::atomic<geni> Head;
int Space[ROOM];
std::atomic<geni> Tail;
bool is_zero(entry& e, int gen)
{
return e.Gen == gen && e.Data.empty();
}
bool is_data(entry& e, int gen)
{
return e.Gen == gen && !e.Data.empty();
}
bool enq(Type val)
{
int prev = 0;
entry ent;
geni tmp;
geni old = tmp = Tail.load(std::memory_order_relaxed);
do
{
ent = Buffer[tmp].load(std::memory_order_relaxed);
while (!is_zero(ent, tmp.Gen))
{
if (ent.Gen < prev)
{
while (!Tail.compare_exchange_weak(old, tmp) && old < tmp);
return false;
}
else tmp.incr();
if(!ent.Data.empty()) prev = ent.Gen;
}
// entry newg { val, tmp.Gen };
} while (!Buffer[tmp].compare_exchange_strong(ent, { val, tmp.Gen }, std::memory_order_release));
tmp.incr();
while (!Tail.compare_exchange_weak(old, tmp) && old < tmp);
return true;
}
Type* deq()
{
entry ent;
geni tmp;
geni old = tmp = Head.load(std::memory_order_relaxed);
do
{
ent = Buffer[tmp].load(std::memory_order_relaxed);
while (!is_data(ent, tmp.Gen))
{
if (ent.Gen == tmp.Gen)
{
while (!Head.compare_exchange_weak(old, tmp) && old < tmp);
return nullptr;
}
else tmp.incr();
}
//entry zero { nullptr, tmp.gen + 1 };
} while (!Buffer[tmp].compare_exchange_strong(ent, { Type(), tmp.Gen + 1 }, std::memory_order_acquire));
tmp.incr();
while (!Head.compare_exchange_weak(old, tmp) && old < tmp);
return &ent.Data;
}
};
//
struct JobDecl
{
void* Job = nullptr;
void* Arg = nullptr;
bool empty()
{
return Job == nullptr;
}
};
void me(int i)
{
printf("me: %d", i);
}
int main()
{
queue<JobDecl, 10> q1;
q1.enq({me, (void*)15});
q1.enq({me, (void*)30});
q1.enq({me, (void*)35});
printf("%d\n", (int)q1.deq()->Arg);
printf("%d\n", (int)q1.deq()->Arg);
printf("%d\n", (int)q1.deq()->Arg);
return 0;
}