-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.cpp
More file actions
94 lines (84 loc) · 1.6 KB
/
CircularQueue.cpp
File metadata and controls
94 lines (84 loc) · 1.6 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
//not tested yet
class CircularQueue{
private:
int size;
int count;
int nextIn;
int nextOut;
mutex bar;
int *p;
static int a;
public:
initialize(int s)
{
p=new int[s];
size=s;
count=0;
nextIn=0;
nextOut=0;
}
bool enqueue(int item)
{
unique_lock<mutex> lck1(bar);
if(size>count)
{
p[nextIn]=item;
nextIn=(nextIn+1)%size;
count++;
return true;
}
return false;
}
int dequeue()
{
unique_lock<mutex> lck1(bar);
if(size>0)
{
int toReturn=p[nextOut];
nextOut=(nextOut+1)%size;
count--;
return toReturn;
}
else
{
throw 1;
}
}
};
void test_enqueue(CircularQueue cq)
{
cq.enqueue(a++);
}
void test_dequeue(CircularQueue cq)
{
cout<<cq.dequeue()<<endl;
}
void testCircularQueue_Normal()
{
CircularQueue cq;
cq.initialize(10);
thread ta(test_enqueue, cq);
thread tb(test_enqueue, cq);
thread tc(test_enqueue, cq);
thread td(test_dequeue, cq);
thread te(test_dequeue, cq);
ta.detach();
tb.detach();
tc.detach();
td.detach();
te.detach();
}
void testCircularQueue_SingleThread()
{
CircularQueue cq;
cq.initialize(1);
assert(true==cq.enqueue(1));
assert(1==cq.dequeue());
}
void testCircularQueue_SingleThreadZero()
{
CircularQueue cq;
cq.initialize(0);
assert(false==cq.enqueue(1));
assert(cq.dequeue());
}