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 "Noncopyable.h"
26#include "sese/Config.h"
27
28#include <functional>
29#include <memory>
30#include <queue>
31#include <mutex>
32
33#ifdef _WIN32
34#pragma warning(disable : 4251)
35#endif
36
37namespace sese {
38
41template<typename T>
43 : public std::enable_shared_from_this<ObjectPool<T>>,
44 public Noncopyable {
45public:
46 using Ptr = std::shared_ptr<ObjectPool<T>>;
47 using ObjectPtr = std::shared_ptr<T>;
48
49 ~ObjectPool() override {
50 while (!queue.empty()) {
51 delete queue.front();
52 queue.pop();
53 }
54 }
55
56 static ObjectPool::Ptr create() noexcept {
57 return std::make_shared_for_overwrite<ObjectPool<T>> ();
58 }
59
60 auto borrow() noexcept {
61 mutex.lock();
62 if (queue.empty()) {
63 mutex.unlock();
64 auto t = new T;
65 return std::shared_ptr<T>(
66 t,
67 [wk_pool = this->weak_from_this()](T *t) { ObjectPool<T>::recycleCallback(wk_pool, t); }
68 );
69 } else {
70 auto t = queue.front();
71 queue.pop();
72 mutex.unlock();
73 return std::shared_ptr<T>(
74 t,
75 [wk_pool = this->weak_from_this()](T *t) { ObjectPool<T>::recycleCallback(wk_pool, t); }
76 );
77 }
78 }
79
80private:
81 ObjectPool() = default;
82
83 static void recycleCallback(const std::weak_ptr<ObjectPool> &wk_pool, T *to_recycle) noexcept {
84 auto pool = wk_pool.lock();
85 if (pool) {
86 // to recycle
87 pool->mutex.lock();
88 pool->queue.emplace(to_recycle);
89 pool->mutex.unlock();
90 } else {
91 // to delete
92 delete to_recycle;
93 }
94 }
95
96 std::mutex mutex;
97 std::queue<T *> queue;
98};
99} // namespace sese