-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathgdnet_queue.h
103 lines (70 loc) · 1.3 KB
/
gdnet_queue.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
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
/* gdnet_rb.h */
#ifndef GDNET_QUEUE_H
#define GDNET_QUEUE_H
#include "os/memory.h"
#include "os/mutex.h"
template<class T, int SIZE = 1024>
class GDNetQueue {
T* items[SIZE];
int read_pos;
int write_pos;
Mutex* mutex;
public:
bool is_empty() {
bool empty;
mutex->lock();
empty = (read_pos == write_pos);
mutex->unlock();
return empty;
}
bool is_full() {
bool full;
mutex->lock();
full = ((write_pos + 1) % SIZE == read_pos);
mutex->unlock();
return full;
}
int size() {
int count;
mutex->lock();
if (write_pos > read_pos)
count = write_pos - read_pos;
else if (write_pos < read_pos)
count = (SIZE - read_pos) + write_pos;
else
count = 0;
mutex->unlock();
return count;
}
void push(T* item) {
ERR_FAIL_COND(is_full());
mutex->lock();
items[write_pos] = item;
write_pos = (write_pos + 1) % SIZE;
mutex->unlock();
}
T* pop() {
ERR_FAIL_COND_V(is_empty(), NULL);
T* item;
mutex->lock();
item = items[read_pos];
read_pos = (read_pos + 1) % SIZE;
mutex->unlock();
return item;
}
void clear() {
mutex->lock();
while (!is_empty()) {
memdelete(pop());
}
mutex->unlock();
}
GDNetQueue() : mutex(NULL) {
read_pos = write_pos = 0;
mutex = Mutex::create();
}
~GDNetQueue() {
memdelete(mutex);
}
};
#endif