forked from mapsme/omim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreaded_priority_queue.hpp
83 lines (61 loc) · 1.22 KB
/
threaded_priority_queue.hpp
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
#pragma once
#include "base/threaded_container.hpp"
#include "std/queue.hpp"
template <typename T>
class ThreadedPriorityQueue : public ThreadedContainer
{
private:
priority_queue<T> m_queue;
public:
template <typename Fn>
void ProcessQueue(Fn const & fn)
{
threads::ConditionGuard g(m_Cond);
bool hadElements = !m_queue.empty();
fn(m_queue);
bool hasElements = !m_queue.empty();
if (!hadElements && hasElements)
m_Cond.Signal();
}
void Push(T const & t)
{
threads::ConditionGuard g(m_Cond);
bool doSignal = m_queue.empty();
m_queue.push(t);
if (doSignal)
m_Cond.Signal();
}
bool WaitNonEmpty()
{
while (m_queue.empty())
{
if (IsCancelled())
break;
m_Cond.Wait();
}
if (IsCancelled())
return true;
return false;
}
T Top(bool doPop)
{
threads::ConditionGuard g(m_Cond);
if (WaitNonEmpty())
return T();
T res = m_queue.top();
if (doPop)
m_queue.pop();
return res;
}
bool Empty() const
{
threads::ConditionGuard g(m_Cond);
return m_queue.empty();
}
void Clear()
{
threads::ConditionGuard g(m_Cond);
while (!m_queue.empty())
m_queue.pop();
}
};