C++ · 完整文件
11_warm_pool.cpp
借出和归还池中资源,观察资源何时可再次使用。
examples/components/11_warm_pool.cpp
1// WarmPool: a pool of reusable object resources.2// Reuse objects to avoid frequent new/delete calls; reset each object to a clean state before lending it.3// Returning an object makes it available for another loan. Useful for repeatedly borrowed messages, connections and similar resources.456789using namespace TwoBufQueue;1011// A pooled object implements reset(generation), which restores its initial state before each loan.12// Returning false rejects this loan and schedules the object for deferred destruction.13struct Message {14 int value = 0;15 bool reset(std::uint64_t) noexcept { value = 0; return true; }16};1718int main() try {19 //---------------1. Initialize: at least 2 and at most 8 objects----------20 // Construction preallocates min_count (2) objects rather than creating them lazily at runtime.21 WarmPool<Message> pool(2, 8);2223 //---------------2. Borrow: get() returns a non-owning Loan---------------24 auto loan = pool.get();25 if (!loan) throw std::runtime_error("get failed"); // Empty if the pool is full or object creation fails.26 loan->value = 42; // Access the object like a pointer.27 if (!pool.is_valid(loan)) throw std::runtime_error("loan should be valid");2829 //---------------3. Return: finish() is equivalent to recycle()-----------30 // finish is [[nodiscard]]: check its result; true means the return succeeded.31 if (!loan.finish()) throw std::runtime_error("recycle failed");3233 // Borrow again: reuse the object just returned; reset() has already cleared value to zero.34 auto again = pool.get();35 if (!again || again->value != 0) throw std::runtime_error("reset not applied on reuse");36 if (!again.finish()) throw std::runtime_error("second recycle failed");3738 //---------------4. Query and preallocate--------------------------------39 if (!pool.all_released()) throw std::runtime_error("not all released");40 // Bring the pool's object count up to 4 in advance to reduce allocation work in later get() calls.41 if (!pool.preallocate(4)) throw std::runtime_error("preallocate failed");42 if (pool.resource_count() != 4) throw std::runtime_error("resource_count mismatch");4344 std::puts("PASS: borrow, recycle, reuse and preallocate");45} catch (const std::exception& error) {46 std::fprintf(stderr, "%s\n", error.what());47 return 1;48}