-
Notifications
You must be signed in to change notification settings - Fork 0
/
d_blockingqueue.hpp
80 lines (68 loc) · 1.75 KB
/
d_blockingqueue.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
//
// Created by denis on 03.12.18.
//
#ifndef UD1_VIEWER_BLOCKINGQUEUE_HPP
#define UD1_VIEWER_BLOCKINGQUEUE_HPP
#include <condition_variable>
#include <deque>
template <typename T>
class BlockingQueue
{
public:
void push(T const& value)
{
{
std::unique_lock<std::mutex> lock(this->_mutex);
_queue.push_front(value);
}
this->_condition.notify_one();
}
void push(T && value)
{
{
std::unique_lock<std::mutex> lock(this->_mutex);
_queue.push_front(std::move(value));
}
this->_condition.notify_one();
}
T pop()
{
std::unique_lock<std::mutex> lock(this->_mutex);
this->_condition.wait(lock, [=]{ return !this->_queue.empty(); });
T rc(std::move(this->_queue.back()));
this->_queue.pop_back();
return rc;
}
bool tryPop (T & v, std::chrono::milliseconds dur)
{
std::unique_lock<std::mutex> lock(this->_mutex);
if (!this->_condition.wait_for(lock, dur, [=]{ return !this->_queue.empty(); }))
{
return false;
}
v = std::move (this->_queue.back());
this->_queue.pop_back();
return true;
}
bool peek(T & v)
{
std::unique_lock<std::mutex> lock(this->_mutex);
if (!_queue.empty())
{
v = std::move (this->_queue.back());
this->_queue.pop_back();
return true;
}
return false;
}
size_t size()
{
std::unique_lock<std::mutex> lock(this->_mutex);
return _queue.size();
}
private:
std::mutex _mutex;
std::condition_variable _condition;
std::deque<T> _queue;
};
#endif //UD1_VIEWER_BLOCKINGQUEUE_HPP