-
Notifications
You must be signed in to change notification settings - Fork 0
/
que.h
79 lines (68 loc) · 1.45 KB
/
que.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
//
// Copyright (c) 2013 Juan Palacios [email protected]
// Subject to the BSD 2-Clause License
// - see < http://opensource.org/licenses/BSD-2-Clause>
//
#ifndef INFIX_QUE_H_
#define INFIX_QUE_H_
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
template <typename T>
class que {
std::queue<T> queue_;
std::mutex mutex_;
std::condition_variable cond_;
bool done_ = false;
public:
T pop();
void pop(T& item);
void push(const T& item);
void finish();
bool isDone();
bool isEmpty();
};
template <typename T>
T que<T>::pop() {
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty()) {
cond_.wait(mlock);
}
auto val = queue_.front();
queue_.pop();
return val;
}
template <typename T>
void que<T>::pop(T& item) {
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty() && !isDone()) {
cond_.wait(mlock);
}
if (isDone() && queue_.empty()) {
item = NULL;
return;
}
item = queue_.front();
queue_.pop();
}
template <typename T>
void que<T>::push(const T& item) {
std::unique_lock<std::mutex> mlock(mutex_);
queue_.push(item);
mlock.unlock();
cond_.notify_one();
}
template <typename T>
void que<T>::finish() {
std::unique_lock<std::mutex> mlock(mutex_);
done_ = true;
mlock.unlock();
cond_.notify_all();
}
template <typename T>
bool que<T>::isDone() {return done_;}
template <typename T>
bool que<T>::isEmpty() {return queue_.empty();}
#endif // INFIX_QUE_H_