| Flutter Impeller |

pool.h
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #pragma once
6
7 #include <memory>
8 #include <mutex>
9
10 namespace impeller {
11
12 /// @brief A thread-safe pool with a limited byte size.
13 /// @tparam T The type that the pool will contain.
14 template <typename T>
15 class Pool {
16 public:
17 explicit Pool(uint32_t limit_bytes) : limit_bytes_(limit_bytes) {}
18
19 std::shared_ptr<T> Grab() {
20 std::scoped_lock lock(mutex_);
21 if (pool_.empty()) {
22 return T::Create();
23 }
24 std::shared_ptr<T> result = std::move(pool_.back());
25 pool_.pop_back();
26 size_ -= result->GetSize();
27 return result;
28 }
29
30 void Recycle(std::shared_ptr<T> object) {
31 std::scoped_lock lock(mutex_);
32 size_t object_size = object->GetSize();
33 if (size_ + object_size <= limit_bytes_ &&
34 object_size < (limit_bytes_ / 2)) {
35 object->Reset();
36 size_ += object_size;
37 pool_.emplace_back(std::move(object));
38 }
39 }
40
41 uint32_t GetSize() const {
42 std::scoped_lock lock(mutex_);
43 return size_;
44 }
45
46 private:
47 std::vector<std::shared_ptr<T>> pool_;
48 const uint32_t limit_bytes_;
49 uint32_t size_ = 0;
50 // Note: This would perform better as a lockless ring buffer.
51 mutable std::mutex mutex_;
52 };
53
54 } // namespace impeller
impeller::Pool::Pool
Pool(uint32_t limit_bytes)
Definition: pool.h:17
impeller::Pool::GetSize
uint32_t GetSize() const
Definition: pool.h:41
impeller::Pool::Grab
std::shared_ptr< T > Grab()
Definition: pool.h:19
impeller::Pool
A thread-safe pool with a limited byte size.
Definition: pool.h:15
impeller::Pool::Recycle
void Recycle(std::shared_ptr< T > object)
Definition: pool.h:30
impeller
Definition: aiks_context.cc:10