C Collections

cmempool · Section 3

cmempool_create_mp

cmempool_create_mp - create a fixed-size memory pool

C Collections (libccollections, -lccollections)

#include <ccollections/cmempool.h>
 
cmempool *cmempool_create_mp(size_t elem_count,
                        size_t elem_size,
                        bool fallback_to_dynamic_memory,
                        bool single_threaded,
                        ccol_memmgmt_procs *mmgmt_procs,
                        char **err);

Creates a memory pool that manages a fixed number of elements of one
size, so every allocation returns an element of that size. A free list
makes each allocation and each free O(1).

elem_count                 Number of elements in the pool (must be > 0)
elem_size                  Size of each element in bytes. It must be > 0.
                          The minimum is sizeof(uintptr_t). The maximum
                          is SIZE_MAX less the stride rounding
fallback_to_dynamic_memory If true, allocate from the heap when the pool
                          is empty
single_threaded           If true, take no lock (faster, but not
                          thread-safe)
mmgmt_procs               Custom memory management, or NULL for the
                          default
err                       Optional pointer that receives an error string

Returns a pointer to the new memory pool on success
Returns NULL on failure

The stride between elements is elem_size rounded up to 16 bytes, and
then up to a power of two unless the library was built with
-DCMEMPOOL_COMPACT_LAYOUT=1 (see doc/building.md in the source
tree). Either way every element, not only the first one, is aligned
for any object type, as malloc() guarantees, so any object that you
can keep in heap memory can go into an entry
An elem_size below sizeof(uintptr_t) is rounded up to it
The call returns NULL with an error in two cases: An elem_size that
would overflow size_t after the stride rounding, and an elem_count and
a stride that together would overflow size_t. A pool holds one stride
for each element and then one status byte for each element, all in one
block
With the fallback on, an allocation from the pool fails only when the
system runs out of memory
The caller must destroy the pool with cmempool_destroy()
The pool calls the functions of mmgmt_procs for its dynamic fallback
entries, and for its own bookkeeping of them, in the middle of an
update of its own state and with its lock held when it has one. Those
functions must not call back into the same pool: With a lock the call
deadlocks, and without one it corrupts that state. An allocator built
on a pool must draw from a different pool
 
Sizing for performance:
 
Give a thread-safe pool at least 8 elements. Below that there is no
room for a cache for each thread, so every allocation and every free
takes the pool's lock and concurrent callers serialise against each
other. 8 is only the floor and not a good size: The cache grows with
the pool, so a pool sized for real use does much better than one of
exactly 8.
 
A pool gives out at most one cache for every 8 elements, and at most
16 in all. A thread that comes when every cache is taken goes through
the pool's lock (one lock for each allocation and each free, the cost
of a pool with no cache) until a thread that holds a cache exits, and
then it gets that one. Size a pool that many threads share so that
each of them gets a cache.
 
A pool that hands out caches allocates a reserve above elem_count, so
that elem_count stays available to any thread however many entries
other threads keep in their own caches. The reserve costs memory: At
most half of elem_count, a quarter at 8192 elements, an eighth at
16384, and a few percent or less from about 65536 upward. It stops
growing once a cache reaches its maximum depth, so a large pool pays
far less for it, in proportion, than a small one.
 
cmempool_total_capacity() reports elem_count, and
cmempool_used_count() counts only the entries that the pool really
handed out, not the ones it only pulled into a cache. What the reserve
changes is how exact the upper end of that count is under concurrent
load. An entry leaves a thread's cache with no lock held, so there is
no count to consult at that moment, and entries go into a cache before
anybody knows whether they will be needed. That choice keeps the
guarantee above, and the price is that concurrent callers can hold a
few entries more than elem_count for a short time, but never more than
elem_count plus the reserve. In either case the memory is allocated
when the pool is created and nothing grows at run time. See
cmempool_total_capacity(3).
 
A thread gets a cache only once it holds a value on a thread-specific
key of the library, because that is how the library frees the cache
when the thread exits. A thread for which this fails goes through the
pool's lock as above, and asks again at its next miss. A process with
no thread-specific key left, or a library that is being unloaded,
gives no pool a cache.
 
A pool created with single_threaded = true never uses the cache, and
neither does a pool created by
cmempool_create_from_preallocated_buffer_mp(); the reserve and the
8-element floor do not apply to them.
 
The best elem_count, elem_size and single_threaded setting depend on
the access pattern, the number of threads and the object lifetimes of
the program that uses the pool. No single choice is best for all of
them, so measure instead of guessing. "make bench" in the source tree
runs the pool's benchmarks beside the system allocator on the current
machine.

Thread-safe when single_threaded is false, in which case the pool uses
a mutex.
 
On the common path a thread-safe pool takes no lock at all. Each
thread keeps a small private cache of entries and goes to the shared
free list only to refill or flush that cache, so threads that allocate
and free at the same time don't contend with each other and the
throughput rises as you add threads.
 
An entry in one thread's cache goes back to the shared free list when
that thread exits, and a destroy of the pool frees its whole block,
those entries included. The allocation of the cache itself is another
matter; cmempool_destroy(3) lists the points at which it goes back
to your allocator. Join a thread before you destroy a pool that it
used. That is enough, because a thread's cleanup runs before
pthread_join() returns.
 
A single_threaded = true pool has no lock and no cache. Never use such
a pool from more than one thread.

cmempool_create(3), cmempool_create_from_preallocated_buffer_mp(3), cmempool_destroy(3), cmempool_alloc_entry(3), cmempool_total_capacity(3)