Sese Framework
x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
ObjectPool.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
23
#pragma once
24
25
#include <
sese/Config.h
>
26
#include <
sese/concurrent/LinkedQueue.h
>
27
#include <
sese/util/Noncopyable.h
>
28
#include <functional>
29
30
namespace
sese::concurrent
{
31
32
// GCOVR_EXCL_START
33
36
template
<
typename
T>
37
class
ObjectPool
:
public
std::enable_shared_from_this<ObjectPool<T>>,
public
Noncopyable
{
38
public
:
40
using
Ptr
= std::shared_ptr<ObjectPool<T>>;
42
using
ObjectPtr
= std::shared_ptr<T>;
43
44
~ObjectPool
()
override
{
45
while
(!
queue
.
empty
()) {
46
T *p =
nullptr
;
47
if
(
queue
.
pop
(p)) {
48
delete
p;
49
}
50
}
51
}
52
55
static
Ptr
create
() {
56
return
std::shared_ptr<ObjectPool<T>>(
new
ObjectPool<T>
);
57
}
58
61
ObjectPtr
borrow
() {
62
T *p =
nullptr
;
63
if
(
queue
.
pop
(p)) {
64
return
std::shared_ptr<T>(
65
p,
66
[wk_pool = this->weak_from_this()](T *t) {
ObjectPool<T>::recycleCallback
(wk_pool, t); }
67
);
68
}
else
{
69
p =
new
T;
70
return
std::shared_ptr<T>(
71
p,
72
[wk_pool = this->weak_from_this()](T *t) {
ObjectPool<T>::recycleCallback
(wk_pool, t); }
73
);
74
}
75
}
76
77
private
:
79
ObjectPool
() =
default
;
80
84
static
void
recycleCallback
(
const
std::weak_ptr<
ObjectPool<T>
> &wk_pool, T *t) {
85
if
(
auto
pool = wk_pool.lock()) {
86
pool->queue.push(t);
87
}
else
{
88
delete
t;
89
}
90
}
91
92
LinkedQueue<T *>
queue
;
93
};
94
95
// GCOVR_EXCL_STOP
96
97
}
// namespace sese::concurrent
sese
concurrent
ObjectPool.h
生成于 2024年 十一月 4日 星期一 09:57:59 , 为 Sese Framework使用
1.11.0