-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadsafe_queue.h
More file actions
67 lines (52 loc) · 1.38 KB
/
threadsafe_queue.h
File metadata and controls
67 lines (52 loc) · 1.38 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
////////////////////////////////////////////////////////////////
template<class T>
class threadsafe_queue
{
public:
void push(T msg);
T front();
void pop();
bool empty();
private:
std::mutex q_mutex;
std::condition_variable cond_var;
std::queue<T> queue;
};
////////////////////////////////////////////////////////////////
template<class T>
void threadsafe_queue<T>::push(T msg)
{
{
std::lock_guard<std::mutex> lock(q_mutex);
queue.push(msg);
}
cond_var.notify_one();
}
////////////////////////////////////////////////////////////////
// warning! calling front() on an empty queue will block until there's something in the queue!
template<class T>
T threadsafe_queue<T>::front()
{
std::unique_lock<std::mutex> lock(q_mutex);
cond_var.wait(lock, [&]{ return !queue.empty(); });
return queue.front();
}
////////////////////////////////////////////////////////////////
template<class T>
void threadsafe_queue<T>::pop()
{
std::lock_guard<std::mutex> lock(q_mutex);
queue.pop();
}
////////////////////////////////////////////////////////////////
template<class T>
bool threadsafe_queue<T>::empty()
{
std::lock_guard<std::mutex> lock(q_mutex);
return queue.size() == 0;
}
////////////////////////////////////////////////////////////////