-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblocking_queue.h
More file actions
51 lines (49 loc) · 1.19 KB
/
Copy pathblocking_queue.h
File metadata and controls
51 lines (49 loc) · 1.19 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
#include <thread>
#include <mutex>
#include <condition_variable>
namespace Nuke{
template<typename T>
struct BlockingQueue{
bool check_full_unguard(){
return ((tail + 1) % capacity) == head % capacity;
}
bool check_empty_unguard(){
return (tail % capacity) == (head % capacity);
}
void push(T && x){
std::unique_lock<std::mutex> lk(mtx);
while (check_full_unguard()){
cv_full.wait(mut);
}
dat[tail] = x;
tail = (tail + 1) % capacity;
cv_empty.notify_one();
}
T pop(){
std::unique_lock<std::mutex> lk(mtx);
while (check_empty_unguard()){
cv_empty.wait(mut);
}
T x = std::move(dat[head]);
head = (head + 1) % capacity;
cv_full.notify_one();
return x;
}
void clear(){
mut.lock();
head = end = 0;
cv_empty.notify_all();
}
BlockingQueue(size_t _capacity) : capacity(_capacity){
dat = new T[capacity];
}
~BlockingQueue(){
delete [] dat;
}
T * dat;
size_t head, tail, capacity;
std::mutex mut;
std::condition_variable cv_empty;
std::condition_variable cv_full;
};
}