-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronizedQueue.hpp
More file actions
70 lines (57 loc) · 1.63 KB
/
SynchronizedQueue.hpp
File metadata and controls
70 lines (57 loc) · 1.63 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
#ifndef _LIBRARY_DATASTRUCTURES_SYNCHRONIZEDQUEUE_HPP
#define _LIBRARY_DATASTRUCTURES_SYNCHRONIZEDQUEUE_HPP
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <deque>
#include <mutex>
#include <optional>
#include <utility>
namespace DataStructures
{
template<typename Data>
requires(std::copyable<Data> || std::movable<Data>)
class SynchronizedQueue
{
std::deque<Data> data;
mutable std::mutex lock;
std::condition_variable conditional;
auto pop_and_return()
{
auto retval = std::move(data.front());
data.pop_front();
return retval;
}
public:
std::optional<Data> try_pop()
{
std::lock_guard<std::mutex> guard(lock);
if (data.empty())
return {};
return pop_and_return();
}
Data wait_and_pop()
{
std::unique_lock<std::mutex> guard(lock);
conditional.wait(guard, [this]() { return !data.empty(); });
return pop_and_return();
}
void push(Data val)
{
std::lock_guard<std::mutex> guard(lock);
data.emplace_back(std::move(val));
conditional.notify_one();
}
size_t was_size() const
{
std::lock_guard<std::mutex> guard(lock);
return data.size();
}
bool was_empty() const
{
std::lock_guard<std::mutex> guard(lock);
return data.empty();
}
};
} // namespace DataStructures
#endif // !_LIBRARY_DATASTRUCTURES_SYNCHRONIZEDQUEUE_HPP