forked from CPqD/RouteFlow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyncQueue.h
74 lines (64 loc) · 1.79 KB
/
SyncQueue.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
#ifndef __SYNC_QUEUE_H__
#define __SYNC_QUEUE_H__
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition.hpp>
template<typename T>
class SyncQueue {
private:
typedef boost::mutex MutexType;
typedef boost::unique_lock<MutexType> ScopedLock;
typedef boost::condition ConditionType;
std::list<T> queue_;
mutable MutexType mutex_;
ConditionType condition_;
public:
bool empty() const {
ScopedLock lock(mutex_);
return queue_.empty();
}
size_t size() const {
ScopedLock lock(mutex_);
return queue_.size();
}
bool front(T& result) const {
ScopedLock lock(mutex_);
if (queue_.empty()) {
return false;
} else {
result = queue_.front();
}
return true;
}
bool back(T& result) const {
ScopedLock lock(mutex_);
if (queue_.empty()) {
return false;
} else {
result = queue_.back();
}
return true;
}
void push(const T& t) {
ScopedLock lock(mutex_);
bool empty = queue_.empty();
queue_.push_back(t);
lock.unlock();
if (empty) {
condition_.notify_one();
}
}
void pop() {
ScopedLock lock(mutex_);
queue_.pop_front();
}
void wait_and_pop(T& result) {
ScopedLock lock(mutex_);
while (queue_.empty()) {
condition_.wait(lock);
}
result = queue_.front();
queue_.pop_front();
}
};
#endif /* __SYNC_QUEUE_H__ */