-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtsqueue.hpp
More file actions
36 lines (30 loc) · 710 Bytes
/
Copy pathtsqueue.hpp
File metadata and controls
36 lines (30 loc) · 710 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
#ifndef THREADSAFEQUEUE_H
#define THREADSAFEQUEUE_H 1
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
template <typename T> class ThreadSafeQueue {
public:
void push(T item) {
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.push(item);
m_cond.notify_one();
}
T pop() {
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait(lock, [this]() { return !m_queue.empty(); });
T item = m_queue.front();
m_queue.pop();
return item;
}
bool empty() {
std::unique_lock<std::mutex> lock(m_mutex);
return m_queue.empty();
}
private:
std::queue<T> m_queue;
std::mutex m_mutex;
std::condition_variable m_cond;
};
#endif