-
Notifications
You must be signed in to change notification settings - Fork 46
/
queue.h
103 lines (81 loc) · 1.74 KB
/
queue.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
103
#pragma once
#include <atomic>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
struct AVPacket;
struct AVFrame;
template <class T>
class Queue {
protected:
// Data
std::queue<T> queue_;
typename std::queue<T>::size_type size_max_;
// Thread gubbins
std::mutex mutex_;
std::condition_variable full_;
std::condition_variable empty_;
// Exit
std::atomic_bool quit_{false};
std::atomic_bool finished_{false};
public:
Queue(const size_t size_max);
bool push(T &&data);
bool pop(T &data);
// The queue has finished accepting input
void finished();
// The queue will cannot be pushed or popped
void quit();
};
using PacketQueue =
Queue<std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>>;
using FrameQueue =
Queue<std::unique_ptr<AVFrame, std::function<void(AVFrame*)>>>;
template <class T>
Queue<T>::Queue(size_t size_max) :
size_max_{size_max} {
}
template <class T>
bool Queue<T>::push(T &&data) {
std::unique_lock<std::mutex> lock(mutex_);
while (!quit_ && !finished_) {
if (queue_.size() < size_max_) {
queue_.push(std::move(data));
empty_.notify_all();
return true;
} else {
full_.wait(lock);
}
}
return false;
}
template <class T>
bool Queue<T>::pop(T &data) {
std::unique_lock<std::mutex> lock(mutex_);
while (!quit_) {
if (!queue_.empty()) {
data = std::move(queue_.front());
queue_.pop();
full_.notify_all();
return true;
} else if (queue_.empty() && finished_) {
return false;
} else {
empty_.wait(lock);
}
}
return false;
}
template <class T>
void Queue<T>::finished() {
finished_ = true;
empty_.notify_all();
}
template <class T>
void Queue<T>::quit() {
quit_ = true;
empty_.notify_all();
full_.notify_all();
}