-
Notifications
You must be signed in to change notification settings - Fork 1
/
priority_blocking_queue.h
92 lines (73 loc) · 2.33 KB
/
priority_blocking_queue.h
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
#pragma once
#include <queue>
#include <mutex>
template <class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>>
class iterable_priority_queue : public std::priority_queue<T, Container, Compare>
{
public:
typename Container::iterator begin() { return std::priority_queue<T, Container, Compare>::c.begin(); }
typename Container::iterator end() { return std::priority_queue<T, Container, Compare>::c.end(); }
};
template <class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>>
class priority_blocking_queue
{
int max_size_;
int size_;
std::mutex m_;
std::condition_variable space_avaible, element_avaible;
iterable_priority_queue<T, Container, Compare> priority_queue_;
public:
priority_blocking_queue() : max_size_(INT_MAX), size_(0) {};
explicit priority_blocking_queue(const int size) : max_size_(size), size_(0) {};
bool add(T t);
bool contains(T t);
void put(T t);
T take();
int size();
};
template <class T, class Container, class Compare>
bool priority_blocking_queue<T, Container, Compare>::add(T t)
{
std::lock_guard<std::mutex> lg(m_);
if (size_ >= max_size_) return false;
size_++;
priority_queue_.push(t);
element_avaible.notify_one();
return true;
}
template <class T, class Container, class Compare>
bool priority_blocking_queue<T, Container, Compare>::contains(T t)
{
std::lock_guard<std::mutex> lg(m_);
for (auto it = priority_queue_.begin(); it != priority_queue_.end(); ++it)
if (*it == t) return true;
return false;
}
template <class T, class Container, class Compare>
void priority_blocking_queue<T, Container, Compare>::put(T t)
{
std::unique_lock<std::mutex> ul(m_);
if (size_ >= max_size_)
space_avaible.wait(ul, [this]() {return size_ < max_size_; });
size_++;
priority_queue_.push(t);
element_avaible.notify_one();
}
template <class T, class Container, class Compare>
T priority_blocking_queue<T, Container, Compare>::take()
{
std::unique_lock<std::mutex> ul(m_);
if (size_ == 0)
element_avaible.wait(ul, [this]() {return size_ > 0; });
T ret = priority_queue_.top();
priority_queue_.pop();
size_--;
space_avaible.notify_one();
return ret;
}
template <class T, class Container, class Compare>
int priority_blocking_queue<T, Container, Compare>::size()
{
std::lock_guard<std::mutex> lg(m_);
return size_;
}