-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThread_Queue.hpp
62 lines (51 loc) · 1.11 KB
/
Thread_Queue.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#pragma once
#include <atomic>
template<typename T, size_t S>
class Thread_Queue
{
private:
std::atomic<unsigned long> ulBeg;
std::atomic<unsigned long> ulEnd;
T tData[S];
public:
Thread_Queue(void) :ulBeg(0), ulEnd(0), tData{}
{}
~Thread_Queue(void) = default;
bool push(T&& tPush)//β²¿²åÈë
{
unsigned long ulCurr = ulEnd.load();
unsigned long ulNext = (ulCurr + 1) % S;
if (ulNext == ulBeg.load())
{
return false;
}
tData[ulCurr] = std::move(tPush);
ulEnd.store(ulNext);//¸üÐÂend
return true;
}
bool pop(T& tPop)//Ç°Ã浯³ö
{
unsigned long ulCurr = ulBeg.load();
unsigned long ulNext = (ulCurr + 1) % S;
if (ulCurr == ulEnd.load())
{
return false;
}
tPop = std::move(tData[ulCurr]);
ulBeg.store(ulNext);
return true;
}
void Clear(void)
{
unsigned long ulBegTemp, ulEndTemp;
do
{
ulBegTemp = ulBeg.load();
ulEndTemp = ulEnd.load();
} while (!ulBeg.compare_exchange_weak(ulBegTemp, ulEndTemp) || ulEndTemp != ulEnd.load());
}
bool Empty(void)
{
return ulBeg.load() == ulEnd.load();
}
};