-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue.hpp
116 lines (103 loc) · 2.14 KB
/
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
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
#ifndef LOCKFREE_QUEUE
#define LOCKFREE_QUEUE
#include "atomics.h"
#include <unistd.h> // usleep
#include <stdlib.h> // rand
namespace lockfree{
template<typename T>
class queue{
private:
class Node{
public:
const T mValue;
Node* mNext;
Node(const T& v):mValue(v),mNext(NULL){}
Node():mValue(),mNext(NULL){};
private:
Node(const Node&);
Node& operator=(const Node&);
};
Node *mHead,*mTail;
// uncopyable
queue(const queue&);
queue& operator=(const queue&);
public:
queue():mHead(new Node()),mTail(mHead){ } // sentinel node
void enq(const T& v){
const Node* const node = new Node(v);
while(1){
const Node* const last = mTail;
const Node* const next = last->mNext;
if(last != mTail){ continue; }
if(next == NULL){
if(compare_and_set(&last->mNext, next, node)){
compare_and_set(&mTail, last, node);
return;
}
}else{
compare_and_set(&mTail, last, next);
}
}
}
T deq(){ // it returns false if there is nothing to deque.
while(1){
const Node* const first = mHead;
const Node* const last = mTail;
const Node* const next = first->mNext;
if(first != mHead){ continue;}
if(first == last){
if(next == NULL){
while(mHead->mNext == NULL){
usleep(1);
}
continue;
//return false;
}
compare_and_set(&mTail,last,next);
}else{
T result = next->mValue;
if(compare_and_set(&mHead, first, next)){
delete first;
return result;
}
}
}
}
bool deq_delete(){ // it destroys dequed item. but fast.
while(1){
const Node* const first = mHead;
const Node* const last = mTail;
const Node* const next = first->mNext;
if(first != mHead){ continue;}
if(first == last){
if(next == NULL){
return false;
}
compare_and_set(&mTail,last,next);
}else{
if(compare_and_set(&mHead, first, next)){
delete first;
return true;
}
}
}
}
bool empty() const{
return mHead->mNext == NULL;
}
bool size() const{
const Node* it = mHead;
int num;
while(it != NULL){
it = it->mNext;
num++;
}
return num-1;
}
~queue(){
while(deq_delete());
delete mHead;
}
};
}; // namepace lockfree
#endif