-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblocking_queue.cpp
60 lines (52 loc) · 1.41 KB
/
blocking_queue.cpp
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
#include "blocking_queue.h"
template<typename T>
void BlockingQueue<T>::Put(const T& task){
std::unique_lock<std::mutex> lock(mtx);
full_.wait(lock, [this]{return (queue_.size() < capacity_);} );
assert(queue_.size() < capacity_);
queue_.push(task);
empty_.notify_all();
}
template<typename T>
T BlockingQueue<T>::Take(){
std::unique_lock<std::mutex> lock(mtx);
empty_.wait(lock, [this]{return !queue_.empty();} );
assert(!queue_.empty());
T front(queue_.front());
queue_.pop();
full_.notify_all();
return front;
}
template<typename T>
size_t BlockingQueue<T>::Size(){
std::lock_guard<std::mutex> lock(mtx);
return queue_.size();
}
template<typename T>
T BlockingQueue<T>::Front(){
std::unique_lock<std::mutex> lock(mtx);
empty_.wait(lock, [this]{return !queue_.empty();} );
assert(!queue_.empty());
T front(queue_.front());
return front;
}
template<typename T>
T BlockingQueue<T>::Back(){
std::unique_lock<std::mutex> lock(mtx);
empty_.wait(lock, [this]{return !queue_.empty();} );
assert(!queue_.empty());
T back(queue_.back());
return back;
}
template<typename T>
bool BlockingQueue<T>::Empty(){
std::unique_lock<std::mutex> lock(mtx);
return queue_.empty();
}
template<typename T>
void BlockingQueue<T>::SetCapacity(const size_t capacity){
capacity_ = (capacity > 0 ? capacity : MAX_CAPACITY);
}
template class BlockingQueue<int>;
template class BlockingQueue<float>;
template class BlockingQueue<double>;