-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcurrentStack.hpp
More file actions
88 lines (67 loc) · 2.04 KB
/
ConcurrentStack.hpp
File metadata and controls
88 lines (67 loc) · 2.04 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
#ifndef _LIBRARY_DATASTRUCTURES_CONCURRENTSTACK_HPP
#define _LIBRARY_DATASTRUCTURES_CONCURRENTSTACK_HPP
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <deque>
#include <mutex>
#include <optional>
#include <type_traits>
#include <vector>
#include <utility>
namespace DataStructures
{
template<typename Data, size_t ContainerSize = 0>
class ConcurrentStack
{
using unbounded_container = std::deque<Data>;
using bounded_container = std::vector<Data>;
std::conditional_t<(ContainerSize > 0), bounded_container, unbounded_container> m_stack;
std::atomic<size_t> m_size;
// synchronization primitives
std::mutex m_lock;
std::condition_variable m_sync;
public:
std::optional<Data> try_pop()
{
std::lock_guard<std::mutex> guard(m_lock);
if (was_empty())
return {};
auto retval = std::move(m_stack.back());
m_stack.pop_back();
--m_size;
return {std::move(retval)};
}
Data wait_and_pop()
{
std::unique_lock<std::mutex> guard(m_lock);
m_sync.wait(guard, [this]() { return not was_empty(); });
auto retval = std::move(m_stack.back());
--m_size;
m_stack.pop_back();
return retval;
}
bool push(Data value)
{
std::lock_guard<std::mutex> guard(m_lock);
if constexpr (ContainerSize > 0)
{
if (m_size == ContainerSize) // container full. can't push new data
return false;
}
m_stack.emplace_back(std::move(value));
++m_size;
m_sync.notify_one();
return true; // success
}
bool was_empty() const
{
return !m_size;
}
size_t was_size() const
{
return m_size;
}
};
} // namespace DataStructures
#endif // !_LIBRARY_DATASTRUCTURES_CONCURRENTSTACK_HPP