-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathThreadSafeQueue.h
More file actions
94 lines (76 loc) · 2.03 KB
/
ThreadSafeQueue.h
File metadata and controls
94 lines (76 loc) · 2.03 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* @file ThreadSafeQueue.h
* @author Supakorn "Jamie" Rassameemasmuang (jamievlin [at] outlook.com)
* @brief A Thread safe queue for sending messages between threads
*/
#pragma once
#include <queue>
#include <mutex>
#include "common.h"
#if defined(HAVE_PTHREAD)
template<typename T>
class ThreadSafeQueue
{
public:
ThreadSafeQueue() = default;
~ThreadSafeQueue() noexcept = default;
ThreadSafeQueue(ThreadSafeQueue const& other)
{
std::lock_guard<std::mutex> lock(other._lockMutex);
_internalQueue = other._internalQueue;
}
ThreadSafeQueue(ThreadSafeQueue&& other) noexcept
{
std::lock_guard<std::mutex> lock(other._lockMutex);
_internalQueue = std::move(other._internalQueue);
}
ThreadSafeQueue& operator= (ThreadSafeQueue const& other) = delete;
ThreadSafeQueue& operator= (ThreadSafeQueue&& other) noexcept = delete;
void enqueue(T const& item)
{
std::lock_guard<std::mutex> lock(_lockMutex);
_internalQueue.push(item);
}
optional<T> dequeue()
{
std::lock_guard<std::mutex> lock(_lockMutex);
if (_internalQueue.empty())
return nullopt;
auto value = make_optional(std::move(_internalQueue.front()));
_internalQueue.pop();
return value;
}
private:
std::queue<T> _internalQueue;
mutable std::mutex _lockMutex;
};
#else
// no thread; calls are already serialized
template<typename T>
class ThreadSafeQueue
{
public:
ThreadSafeQueue() = default;
~ThreadSafeQueue() = default;
ThreadSafeQueue(ThreadSafeQueue const& other) = default;
ThreadSafeQueue(ThreadSafeQueue&& other) noexcept = default;
ThreadSafeQueue& operator=(ThreadSafeQueue const& other)= delete;
ThreadSafeQueue& operator=(ThreadSafeQueue&& other) noexcept= delete;
void enqueue(T const& item)
{
_internalQueue.push(item);
}
optional<T> dequeue()
{
if (_internalQueue.empty())
{
return nullopt;
}
auto value= make_optional(std::move(_internalQueue.front()));
_internalQueue.pop();
return value;
}
private:
std::queue<T> _internalQueue;
};
#endif