-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_queue.h
58 lines (48 loc) · 1.15 KB
/
message_queue.h
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
/* Adapted from
www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
*/
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename MessageType>
class message_queue
{
public:
void push(MessageType const& message)
{
std::unique_lock<std::mutex> lock(the_mutex);
the_queue.push(message);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(the_mutex);
return the_queue.empty();
}
bool try_pop(MessageType& popped_value)
{
std::lock_guard<std::mutex> lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(MessageType& popped_value)
{
std::unique_lock<std::mutex> lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
private:
std::queue<MessageType> the_queue;
mutable std::mutex the_mutex;
std::condition_variable the_condition_variable;
};