-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy paththread_safe_queue.cpp
More file actions
40 lines (31 loc) · 963 Bytes
/
thread_safe_queue.cpp
File metadata and controls
40 lines (31 loc) · 963 Bytes
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
#include "mach/thread_safe_queue.hpp"
#include <unordered_map>
// Explicit instantiation of the template class, used in grpc_client.hpp.
template class ThreadSafeQueue<std::pair<long, std::unordered_map<std::string, double>>>;
template <typename T>
void ThreadSafeQueue<T>::push(T item) {
// Acquire lock
std::unique_lock<std::mutex> lock(m_mutex);
// Add item
m_queue.push(item);
// Notify one thread that
// is waiting
m_cond.notify_one();
}
template <typename T>
T ThreadSafeQueue<T>::pop() {
// acquire lock
std::unique_lock<std::mutex> lock(m_mutex);
// wait until queue is not empty
m_cond.wait(lock, [this]() { return !m_queue.empty(); });
// retrieve item
T item = m_queue.front();
m_queue.pop();
// return item
return item;
}
template <typename T>
size_t ThreadSafeQueue<T>::size() {
std::unique_lock<std::mutex> lock(m_mutex);
return m_queue.size();
}