-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfifo.hpp
More file actions
51 lines (45 loc) · 1.1 KB
/
fifo.hpp
File metadata and controls
51 lines (45 loc) · 1.1 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
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
template <typename type>
class fifo {
private:
std::queue<type> q;
std::mutex mtx;
std::condition_variable cv;
public:
// void write(type& elem) {
// std::lock_guard<std::mutex> lock(mtx);
// q.push(elem);
// cv.notify_one();
// }
void write(type elem) {
std::lock_guard<std::mutex> lock(mtx);
q.push(elem);
cv.notify_one();
}
type read(void) { // blocking read
std::unique_lock<std::mutex> lock(mtx);
if (q.empty()) { // main & callback threads, no spurious wakeup
cv.wait(lock);
}
type elem = q.front();
q.pop();
return elem;
}
bool peek(type& elem) { // non-blocking attempt to read
std::lock_guard<std::mutex> lock(mtx);
if (q.empty()) {
return false;
} else {
elem = q.front();
q.pop();
return true;
}
}
unsigned size(void) {
std::lock_guard<std::mutex> lock(mtx);
return q.size();
}
};