-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConcurrentQueue.h
102 lines (77 loc) · 1.84 KB
/
ConcurrentQueue.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
93
94
95
96
97
98
99
100
101
102
#pragma once
#include <boost/thread/thread.hpp>
#include <queue>
template<typename T>
class ConcurrentQueue
{
public:
typedef boost::mutex Mutex;
typedef boost::mutex::scoped_lock ScopedLock;
typedef boost::condition_variable ConditionVariable;
ConcurrentQueue() :
maxSize_(100),
aborted_(false)
{
}
virtual ~ConcurrentQueue() {}
bool push(T const & item)
{
ScopedLock lock(mutex_);
while (queue_.size() >= maxSize_ && ! aborted_) {
condVarPop_.wait(lock);
}
if (aborted_) {
return false;
}
queue_.push(item);
lock.unlock();
condVarPush_.notify_one();
return true;
}
bool pop(T & item)
{
ScopedLock lock(mutex_);
while (queue_.empty() && ! aborted_) {
condVarPush_.wait(lock);
}
if (aborted_ && queue_.empty()) {
return false;
}
item = queue_.front();
queue_.pop();
condVarPop_.notify_one();
return true;
}
bool empty() const
{
ScopedLock lock(mutex_);
return queue_.empty();
}
bool size() const
{
ScopedLock lock(mutex_);
return queue_.size();
}
void abort()
{
ScopedLock lock(mutex_);
aborted_ = true;
condVarPop_.notify_all();
condVarPush_.notify_all();
}
unsigned int getMaxSize()
{
return maxSize_;
}
void setMaxSize(const int & size)
{
maxSize_ = size;
}
protected:
bool aborted_;
unsigned int maxSize_;
std::queue<T> queue_;
mutable Mutex mutex_;
ConditionVariable condVarPush_;
ConditionVariable condVarPop_;
};