forked from pixop/video-compare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.h
115 lines (91 loc) · 2.07 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
104
105
106
107
108
109
110
111
112
113
114
115
#pragma once
#include <atomic>
#include <condition_variable>
#include <functional>
#include <iostream>
#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:
explicit Queue(size_t size_max);
bool push(T&& data);
bool pop(T& data);
// The queue has finished accepting input
bool is_finished();
void finished();
// The queue will cannot be pushed or popped
void quit();
void empty();
};
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;
}
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;
}
if (queue_.empty() && finished_) {
return false;
}
empty_.wait(lock);
}
return false;
}
template <class T>
bool Queue<T>::is_finished() {
return finished_;
}
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();
}
template <class T>
void Queue<T>::empty() {
std::unique_lock<std::mutex> lock(mutex_);
while (!queue_.empty()) {
queue_.pop();
}
full_.notify_all();
}