Sese Framework
x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
BufferedQueue.h
浏览该文件的文档.
1
// Copyright 2024 libsese
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
// http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
19
20
#pragma once
21
22
#include <queue>
23
#include <
sese/thread/Locker.h
>
24
25
namespace
sese
{
26
28
template
<
class
T>
29
class
BufferedQueueNn
{
30
public
:
31
explicit
BufferedQueueNn
(
size_t
write_limit) :
writeLimit
(write_limit) {}
32
33
bool
pop
(T &t) {
34
Locker
locker(
readMutex
);
35
if
(
readQueue
.empty()) {
36
writeMutex
.lock();
37
swap
();
38
writeMutex
.unlock();
39
if
(
readQueue
.empty()) {
40
return
false
;
41
}
else
{
42
t =
readQueue
.front();
43
readQueue
.pop();
44
return
true
;
45
}
46
}
else
{
47
t =
readQueue
.front();
48
readQueue
.pop();
49
return
true
;
50
}
51
}
52
53
bool
push
(
const
T &t) {
54
Locker
locker(
writeMutex
);
55
if
(
writeQueue
.size() >=
writeLimit
) {
56
return
false
;
57
}
else
{
58
writeQueue
.push(t);
59
return
true
;
60
}
61
}
62
63
private
:
64
void
swap
() {
65
std::swap(
q1
,
q2
);
66
}
67
68
private
:
69
std::queue<T>
q1
;
70
std::queue<T>
q2
;
71
72
std::queue<T> &
writeQueue
=
q1
;
73
std::queue<T> &
readQueue
=
q2
;
74
75
std::mutex
writeMutex
;
76
std::mutex
readMutex
;
77
78
size_t
writeLimit
;
79
};
80
82
template
<
class
T>
83
using
BufferedQueueN1
=
BufferedQueueNn<T>
;
84
86
template
<
class
T>
87
using
BufferedQueue1N
=
BufferedQueueNn<T>
;
88
90
template
<
class
T>
91
class
BufferedQueue11
{
92
public
:
93
explicit
BufferedQueue11
(
size_t
write_limit) :
writeLimit
(write_limit) {}
94
95
bool
pop
(T &t) {
96
Locker
locker(
mutex
);
97
if
(
queue
.empty()) {
98
return
false
;
99
}
else
{
100
t =
queue
.front();
101
queue
.pop();
102
return
true
;
103
}
104
}
105
106
bool
push
(
const
T &t) {
107
Locker
locker(
mutex
);
108
if
(
queue
.size() >=
writeLimit
) {
109
return
false
;
110
}
else
{
111
queue
.push(t);
112
return
true
;
113
}
114
}
115
116
private
:
117
std::queue<T>
queue
;
118
119
std::mutex
mutex
;
120
121
size_t
writeLimit
;
122
};
123
124
}
// namespace sese
sese
container
BufferedQueue.h
生成于 2024年 十一月 4日 星期一 09:57:59 , 为 Sese Framework使用
1.11.0