CKTIS / C++
std::pmr::synchronized_pool_resource — synchronized memory pooling
std::pmr::synchronized_pool_resource manages pools of memory blocks and supports concurrent access from multiple threads. It can supply storage to PMR containers, but resource synchronization does not make concurrent modifications of a container safe.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <memory_resource>
std::pmr::synchronized_pool_resource pool;
std::pmr::synchronized_pool_resource configured(options, upstream);std::pmr::synchronized_pool_resource, declared in <memory_resource>, is a memory resource managing pools of differently sized blocks. It obtains larger chunks from an upstream resource and divides them into blocks. Requests exceeding the largest size handled by its pools go directly to upstream.
Multiple threads may access this resource without external synchronization. This does not mean that a shared container using it can be modified concurrently without restrictions. In contrast, std::pmr::unsynchronized_pool_resource does not permit simultaneous access from multiple threads.
The default constructor selects std::pmr::get_default_resource() as upstream. Another constructor accepts std::pmr::pool_options and an upstream pointer; the resource does not take ownership of upstream. max_blocks_per_chunk and largest_required_pool_block tune pooling, but the implementation may adjust their values. options() returns the settings in use.
The resource must outlive containers using it, and upstream must remain valid while it is used. release() returns all allocated memory, including outstanding blocks, without invoking stored objects' destructors. Destroy objects and containers before calling release(). The resource's destructor also releases its memory.
The example creates a std::pmr::vector<int> backed by the pool and prints the sum of its elements. The inner scope destroys the vector before release(). It assumes neither a particular allocation count nor reuse of a particular address.
Examples
#include <iostream>
#include <memory_resource>
#include <vector>
int main() {
std::pmr::synchronized_pool_resource pool;
{
std::pmr::vector<int> values{&pool};
values.reserve(3);
values.push_back(10);
values.push_back(20);
values.push_back(30);
int sum = 0;
for (int value : values) {
sum += value;
}
std::cout << sum << '\n';
}
pool.release();
}
Result
60
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.