Sese Framework  2.3.0
A cross-platform framework
Loading...
Searching...
No Matches
ObjectPool.h
Go to the documentation of this file.
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>
28#include <functional>
29
30namespace sese::concurrent {
31
32// GCOVR_EXCL_START
33
36template<typename T>
37class ObjectPool : public std::enable_shared_from_this<ObjectPool<T>>, public Noncopyable {
38public:
39 using Ptr = std::shared_ptr<ObjectPool<T>>;
40 using ObjectPtr = std::shared_ptr<T>;
41
42 ~ObjectPool() override {
43 while (!queue.empty()) {
44 T *p = nullptr;
45 if (queue.pop(p)) {
46 delete p;
47 }
48 }
49 }
50
53 static Ptr create() {
54 return std::shared_ptr<ObjectPool<T>>(new ObjectPool<T>);
55 }
56
60 T *p = nullptr;
61 if (queue.pop(p)) {
62 return std::shared_ptr<T>(
63 p,
64 [wk_pool = this->weak_from_this()](T *t) { ObjectPool<T>::recycleCallback(wk_pool, t); }
65 );
66 } else {
67 p = new T;
68 return std::shared_ptr<T>(
69 p,
70 [wk_pool = this->weak_from_this()](T *t) { ObjectPool<T>::recycleCallback(wk_pool, t); }
71 );
72 }
73 }
74
75private:
76 ObjectPool() = default;
77
81 static void recycleCallback(const std::weak_ptr<ObjectPool<T>> &wk_pool, T *t) {
82 if (auto pool = wk_pool.lock()) {
83 pool->queue.push(t);
84 } else {
85 delete t;
86 }
87 }
88
90};
91
92// GCOVR_EXCL_STOP
93
94} // namespace sese::concurrent