-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadSafeQueue.hpp
42 lines (37 loc) · 906 Bytes
/
ThreadSafeQueue.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
#pragma once
#include <condition_variable>
#include <mutex>
#include <queue>
template <typename T>
class ThreadSafeQueue {
public:
ThreadSafeQueue()
{
}
void enqueue(T obj)
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::move(obj));
// condition.notify_one();
}
bool isEmpty() const
{
std::lock_guard<std::mutex> lock(mutex);
return queue.empty();
}
T dequeue()
{
std::unique_lock<std::mutex> lock(mutex);
// while (queue.empty())
// condition.wait(lock);
if (queue.empty())
throw std::runtime_error("Trying to get object from empty queue");
T val = std::move(queue.front());
queue.pop();
return val;
}
private:
std::queue<T> queue;
mutable std::mutex mutex;
std::condition_variable condition;
};