-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.hpp
104 lines (83 loc) · 1.67 KB
/
Queue.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
//
// Created by lining on 10/1/22.
//
#ifndef _QUEUE_H
#define _QUEUE_H
#include <queue>
#include <thread>
#include <mutex>
using namespace std;
template<typename T>
class Queue {
public:
Queue() {
if (mtx == nullptr){
mtx = new std::mutex();
}
}
Queue(unsigned int max) {
if (mtx == nullptr){
mtx = new std::mutex();
}
setMax(max);
}
~Queue() {
delete mtx;
}
bool push(T t) {
if (isSetMax) {
if (q.size() >= max) {
return false;
}
}
std::unique_lock<std::mutex> lock(*mtx);
q.push(t);
return true;
}
bool pop(T &t) {
if (q.empty()) {
return false;
}
std::unique_lock<std::mutex> lock(*mtx);
t = q.front();
q.pop();
return true;
}
bool front(T &t) {
if (q.empty()) {
return false;
}
std::unique_lock<std::mutex> lock(*mtx);
t = q.front();
return true;
}
bool back(T &t) {
if (q.empty()) {
return false;
}
std::unique_lock<std::mutex> lock(*mtx);
t = q.back();
return true;
}
void setMax(int value) {
max = value;
isSetMax = true;
}
int size() {
return q.size();
}
bool empty() {
return q.empty();
}
void clear() {
queue<T> q1;
swap(q, q1);
}
private:
// 如何保证对这个队列的操作是线程安全的?引入互斥锁
queue<T> q;
int max;
bool isSetMax = false;
std::mutex *mtx= nullptr;
};
#endif //_QUEUE_H