-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_queue.hpp
58 lines (48 loc) · 1.12 KB
/
sync_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
#pragma once
#include <condition_variable>
#include <mutex>
#include <queue>
template<typename T>
class sync_queue
{
public:
void push(T &&data)
{
std::lock_guard<std::mutex> guard(write_mutex);
queue.push(std::forward<T>(data));
not_empty.notify_one();
}
T pop()
{
std::unique_lock<std::mutex> guard(write_mutex);
if(queue.empty())
{
not_empty.wait(guard);
}
T data = queue.front();
queue.pop();
return data;
}
sync_queue &operator<<(T &&data)
{
std::lock_guard<std::mutex> guard(write_mutex);
queue.push(std::forward<T>(data));
not_empty.notify_one();
return *this;
}
sync_queue &operator>>(T &data)
{
std::unique_lock<std::mutex> guard(write_mutex);
if(queue.empty())
{
not_empty.wait(guard);
}
data = queue.front();
queue.pop();
return *this;
}
private:
std::queue<T> queue;
std::mutex write_mutex;
std::condition_variable not_empty;
};