-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomQueue.hpp
117 lines (92 loc) · 2.07 KB
/
CustomQueue.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
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
116
117
#pragma once
#ifndef __CUSTOM_QUEUE_V0__
#define __CUSTOM_QUEUE_V0__
#include <atomic>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
struct AVPacket;
struct AVFrame;
template <typename T>
class CustomQueue
{
public:
CustomQueue (const size_t sizeMax);
bool push(T &&data);
bool pop(T &data);
void finished();
void quit();
private:
std::queue<T> queue;
typename std::queue<T>::size_type mSizeMax;
std::mutex mutex;
std::condition_variable fullQueue;
std::condition_variable emptyQueue;
std::atomic_bool mQuit{false};
std::atomic_bool mFinished{false};
};
using PacketQueue = CustomQueue<std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>>;
using FrameQueue = CustomQueue<std::unique_ptr<AVFrame, std::function<void(AVFrame*)>>>;
template <typename T>
CustomQueue<T>::CustomQueue(const size_t sizeMax): mSizeMax{sizeMax}
{
}
template <typename T>
bool CustomQueue<T>::push(T &&data)
{
std::unique_lock<std::mutex> lock(mutex);
while(!mQuit && !mFinished)
{
if(queue.size() < mSizeMax)
{
queue.push(std::move(data));
emptyQueue.notify_all();
return true;
}
else
{
fullQueue.wait(lock);
}
}
return false;
}
template <typename T>
bool CustomQueue<T>::pop(T &data)
{
std::unique_lock<std::mutex> lock(mutex);
while(!mQuit)
{
if(!queue.empty())
{
data = std::move(queue.front());
queue.pop();
fullQueue.notify_all();
return true;
}
else if(queue.empty() && mFinished)
{
return false;
}
else
{
emptyQueue.wait(lock);
}
}
return false;
}
template <typename T>
void CustomQueue<T>::finished()
{
mFinished = true;
emptyQueue.notify_all();
}
template <typename T>
void CustomQueue<T>::quit()
{
mQuit = true;
emptyQueue.notify_all();
fullQueue.notify_all();
}
#endif //__CUSTOM_QUEUE_V0__