-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafequeue.h
More file actions
59 lines (49 loc) · 1.17 KB
/
Copy pathsafequeue.h
File metadata and controls
59 lines (49 loc) · 1.17 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
#ifndef SAFE_QUEUE
#define SAFE_QUEUE
#include <queue>
#include <mutex>
#include <optional>
template <typename T>
class ThreadsafeQueue
{
std::queue<T> queue_;
mutable std::mutex mutex_;
// Moved out of public interface to prevent races between this
// and pop().
bool empty() const
{
return queue_.empty();
}
public:
ThreadsafeQueue() = default;
ThreadsafeQueue(const ThreadsafeQueue<T> &) = delete;
ThreadsafeQueue &operator=(const ThreadsafeQueue<T> &) = delete;
ThreadsafeQueue(ThreadsafeQueue<T> &&other)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_ = std::move(other.queue_);
}
virtual ~ThreadsafeQueue() {}
unsigned long size() const
{
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
std::optional<T> pop()
{
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty())
{
return {};
}
T tmp = queue_.front();
queue_.pop();
return tmp;
}
void push(const T &item)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(item);
}
};
#endif