-
Notifications
You must be signed in to change notification settings - Fork 0
/
cusdr_queue.h
122 lines (94 loc) · 2.2 KB
/
cusdr_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
116
117
118
119
120
121
122
#ifndef CUSDR_QUEUE_H
#define CUSDR_QUEUE_H
#include <QQueue>
#include <QSemaphore>
#include <QMutex>
template<class T> class QHQueue {
public:
QHQueue(int maxSize = 1024*1000) : m_semFree(maxSize), m_semUsed(0)
{
m_max_size = maxSize;
}
void enqueue(const T &value) {
m_semFree.acquire(1);
m_mutex.lock();
m_queue.enqueue(value);
m_mutex.unlock();
m_semUsed.release(1);
}
T dequeue() {
m_semUsed.acquire(1);
m_mutex.lock();
T val = m_queue.dequeue();
m_mutex.unlock();
m_semFree.release(1);
return val;
}
T head() {
m_semUsed.acquire(1);
m_mutex.lock();
T val = m_queue.head();
m_mutex.unlock();
m_semFree.release(1);
}
bool isEmpty() const {
return m_semUsed.available() == 0;
}
bool isFull() const {
return m_semFree.available() == 0;
}
int count() const {
return m_semUsed.available();
}
void release_queue() {
m_semUsed.release(1);
}
/*void setMaxSize(int maxSize) {
m_mutex.lock();
delete &m_semFree;
QSemaphore m_semFree(maxSize);
m_mutex.unlock();
}*/
T tryHead() {
bool t = m_semUsed.tryAcquire(1);
if (!t)
return T();
m_mutex.lock();
T val = m_queue.head();
m_mutex.unlock();
m_semFree.release(1);
return val;
}
T tryDequeue(int *j) {
bool t = m_semUsed.tryAcquire(1);
if (!t)
{
*j = 0;
T val = (char)'*';
return val;
}
else
*j = 1;
m_mutex.lock();
T val = m_queue.dequeue();
m_mutex.unlock();
m_semFree.release(1);
return val;
}
void clear() {
m_mutex.lock();
m_queue.clear();
int avail = m_semUsed.available();
m_semUsed.acquire(avail); // available -> 0
avail = m_semFree.available();
m_semFree.release(m_max_size - avail); // avilable -> m_max_size
m_mutex.unlock();
}
private:
QQueue<T> m_queue;
QSemaphore m_semFree;
QSemaphore m_semUsed;
QMutex m_mutex;
int m_max_size;
};
#endif // CUSDR_QUEUE_H