This repository has been archived by the owner on Oct 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_queue.hpp
78 lines (64 loc) · 1.62 KB
/
shared_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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef MUSH_SHARED_QUEUE
#define MUSH_SHARED_QUEUE
#include <queue>
#include <mutex>
#include <condition_variable>
namespace mush
{
template <typename T>
class shared_queue
{
public:
shared_queue() = default;
~shared_queue() = default;
T& front();
void pop();
void push(const T& item);
void push(T item);
int size();
bool empty();
private:
std::queue<T> queue;
std::mutex queue_lock;
std::condition_variable condition;
};
template <typename T>
T& shared_queue<T>::front()
{
std::unique_lock<std::mutex> lock(queue_lock);
while (queue.empty())
condition.wait(lock);
return queue.front();
}
template <typename T>
void shared_queue<T>::pop()
{
std::unique_lock<std::mutex> lock(queue_lock);
while(queue.empty())
condition.wait(lock);
queue.pop();
}
template <typename T>
void shared_queue<T>::push(const T& item)
{
std::unique_lock<std::mutex> lock(queue_lock);
queue.push(item);
lock.unlock();
condition.notify_one();
}
template <typename T>
void shared_queue<T>::push(T item)
{
std::unique_lock<std::mutex> lock(queue_lock);
queue.push(std::move(item));
lock.unlock();
condition.notify_one();
}
template <typename T>
int shared_queue<T>::size()
{
std::unique_lock<std::mutex> lock(queue_lock);
return queue.size();
}
}
#endif