VLink  2.0.0
A high-performance communication middleware
object_pool.h 文件参考

Thread-safe generic object pool with RAII handles and a tunable reset policy. 更多...

#include <memory>
#include <mutex>
#include <utility>
#include <vector>
#include "./functional.h"
#include "./macros.h"
object_pool.h 的引用(Include)关系图:

浏览源代码.

class  vlink::ObjectPoolBase
 Type-independent base of ObjectPool that owns counters, mutex and policy state. 更多...
 
struct  vlink::ObjectPoolBase::Stats
 Point-in-time snapshot of internal pool counters. 更多...
 
class  vlink::ObjectPool< T >
 Thread-safe recycling pool for instances of T with RAII acquisition. 更多...
 
struct  vlink::ObjectPool< T >::PoolDeleter
 Custom deleter installed on every RAII handle handed out by get / get_shared. 更多...
 

命名空间

 

详细描述

Thread-safe generic object pool with RAII handles and a tunable reset policy.

ObjectPool<T> recycles previously allocated T instances so that hot paths avoid repeated heap traffic. Callers acquire an object through one of three entry points, use it, and then either let RAII return it automatically or hand it back manually.

Acquisition variants:

Method Returned handle Returns to pool automatically
get() unique_ptr<T, PoolDeleter> Yes, on unique_ptr destruction
get_shared shared_ptr<T> Yes, on last shared_ptr release
borrow() Raw T* No, caller must invoke give_back

Reset-policy decision table for the optional ResetCallback:

Policy Reset on acquire Reset on release Typical use
kPolicyNone No No Pure / stateless objects
kPolicyRelease No Yes Default; scrub on the return path
kPolicyAcquire Yes No Scrub right before use
kPolicyBoth Yes Yes Defence-in-depth scrubbing

Lifecycle of a pooled object:

*   factory ---> free list <----------+
*                  |  acquire         |
*                  v                  |
*               in use ---> release --+   (reset on release if enabled)
*                  ^                  |
*                  +--reset-on-acquire+
* 
Thread safety
Every public method acquires the internal mutex so concurrent callers may interleave freely. Factory and reset callbacks run outside the mutex.
Example
auto pool = std::make_shared<vlink::ObjectPool<Buffer>>(
[]{ return std::make_unique<Buffer>(4096); },
4,
16,
[](Buffer& buf){ buf.clear(); },
{
auto buf = pool->get();
buf->write(payload.data(), payload.size());
}
Buffer* raw = pool->borrow();
raw->write(payload.data(), payload.size());
pool->give_back(raw);