-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsafe_queue.hpp
127 lines (106 loc) · 2.25 KB
/
safe_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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#ifndef SAFE_QUEUE_HPP
#define SAFE_QUEUE_HPP
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
/**
* @class safe_queue
* @author Michael Griffin
* @date 15/08/2015
* @file safe_queue.hpp
* @brief Multi-Thread Safe Message Queue
*/
template <class T>
class SafeQueue
{
public:
explicit SafeQueue(void) :
q(),
m(),
c()
{}
// Copy Constructor (Overridden with MOVE)
SafeQueue& operator=(SafeQueue& other)
{
if(this != &other)
{
std::lock_guard<std::mutex> lock(m);
if(!&other.isEmpty())
{
q = other.q;
m = other.m;
c = other.c;
}
}
return *this;
}
// Move Constructor.
SafeQueue& operator=(SafeQueue&& other)
{
if(this != &other)
{
std::lock_guard<std::mutex> lock(m);
if(!other.isEmpty())
{
q.swap(other.q);
}
}
return *this;
}
~SafeQueue(void)
{
std::queue<T>().swap(q);
}
// Add Item to Queue.
//void enqueue(const T& t)
void enqueue(T t)
{
std::lock_guard<std::mutex> lock(m);
q.push(t);
c.notify_one();
}
// Get first Item in Queue. FIFO
T dequeue(void)
{
if (q.empty())
return nullptr;
std::unique_lock<std::mutex> lock(m);
T val = q.front();
q.pop();
return val;
}
// Clear out the Entire Queue.
void clear(void)
{
std::lock_guard<std::mutex> lock(m);
std::queue<T>().swap(q);
}
// Check for Non-Blocking Wait.
bool isEmpty(void) const
{
return q.empty();
}
// Check for Non-Blocking Wait.
unsigned long size(void) const
{
return q.size();
}
SafeQueue& copy(SafeQueue&& other)
{
if(this != &other)
{
std::lock_guard<std::mutex> lock(m);
if(!other.isEmpty())
{
q.swap(other.q);
}
}
return *this;
}
private:
std::queue<T> q;
mutable std::mutex m;
std::condition_variable c;
};
#endif // SAFE_QUEUE_HPP