C Collections

clrucache · Section 3

clrucache_create_full

clrucache_create_full - create an LRU cache with full control

C Collections (libccollections, -lccollections)

#include <ccollections/clrucache.h>
 
ccache clrucache_create_full(size_t capacity,
                             ccol_data_type key_type,
                             ccol_data_type val_type,
                             ccache_remote_getter_fn getter,
                             ccache_remote_setter_fn setter,
                             ccache_eviction_fn eviction_cb,
                             ccol_memmgmt_procs *mprocs,
                             char **err);

Creates a thread-safe Least Recently Used (LRU) cache, with O(1)
lookup through a hash map and O(1) eviction through a doubly-linked
list. The cache holds up to capacity live entries, and an insert past
that limit first evicts the least recently used entry.
 
The cache is divided into segments, each with its own lock, and a key
belongs to exactly one segment. Threads working on keys in different
segments don't wait for each other, so the throughput holds up as you
add threads. Each segment evicts on its own; see NOTES.
 
This is the low-level constructor, and application code should use
the ccache_construct() macro family instead.

capacity     The total number of live entries that the cache holds.
             From 128 up, each segment evicts when its own share is
             full; see NOTES. A capacity of 0 is refused: The call
             fails, and the string in *err contains
             "capacity must be > 0".
key_type     The ccol_data_type of the keys, as
             ccol_determine_ccol_data_type() returns it.
val_type     The ccol_data_type of the values. It is only used for
             type tracking, because the internal map always stores
             heap pointers.
getter       Remote getter callback, or NULL. It is called on a cache
             miss to fetch the value from an external source. On
             success it must allocate the value data on the heap,
             assign that pointer to val->ptr, set val->size to the
             byte length and return true. The cache takes ownership
             of val->ptr and frees it with its own allocator, which is
             mprocs if the caller gives one and malloc()/free() if
             not. The getter must allocate with that same allocator,
             or the cache's later free corrupts the heap. On failure
             the getter must leave val->ptr as NULL and return false.
setter       Remote setter callback, or NULL. It is called
             synchronously before each update of the cache, with the
             key and the value as const cmap_pair* pointers. When it
             returns false, the cache is not updated.
             The getter and the setter are called with no lock of the
             cache held, so either one can use the cache for any
             other key. Neither must call back into the same cache for
             the key it serves: A get or a set of that key waits for
             the operation that runs the callback, and the thread
             deadlocks against itself. Neither must destroy the
             cache, because the destroy waits for that same call.
eviction_cb  Eviction callback, or NULL. It is called when an entry is
             evicted to make room, and also for each entry that is in
             the cache when ccache_destroy() runs. In both cases the
             lock of the owning segment is held during the call. The
             callback gets the evicted key and value as
             const cmap_pair* pointers.
             It must not call back into the cache, and it is not
             serialised against itself; see NOTES.
mprocs       Custom memory management procedures, or NULL for the
             default malloc and free. The cache keeps a copy of the
             struct, so the caller may release or reuse the struct
             once this call returns, but the functions it names must
             stay callable until the cache is destroyed.
err          An optional pointer that gets an error string on failure.

Returns a new cache handle on success.
Returns CCACHE_NULL on failure, and sets *err when err is not
NULL.
A create from a destructor that runs after the library's destructor
fails as well, because by then the library has released its table of
cache handles for the end of the process.
CCACHE_NULL is ((ccache)0), and it plays the same role for
a ccache as NULL does for a pointer. Compare a handle directly
against it, or use the handle as a condition: If (!cache) is a correct
test for an invalid handle.

A key of a type that the cache doesn't know (ccol_other_types, such as a struct) is the same key as another one only when every byte of the two is equal. Both the choice of segment and the internal map read every byte of the key, padding bytes of a struct included, so two keys with equal members but different padding are two different keys and a lookup misses.

The cache takes no custom hash or key equality function, so the bytes of a padded key must be fully determined. Through the raw functions, such as clrucache_set_full(3), the cache reads exactly the object that key_pair->ptr points at, so zero the whole key object with memset() before you set its members. Through ccache_get(3) and ccache_set(3) the cache sees the macro's own copy of the key, and C leaves the padding of a struct copy unspecified. With GCC 11 or later the macros set that padding to zero; with any other compiler, use the raw functions for a padded key.

The handle that the function gives back is an opaque VALUE, not a
pointer. Don't cast it to void*, don't cast a void* to it, and don't
use it as an address.
The cache is thread-safe: Per-segment locks and per-entry condition
variables protect every operation on the handle. Operations on the
same key are still serialised against each other, and the coalescing
of concurrent misses for one key depends on that.
 
The division starts at a capacity of 128, the first capacity that
gives two segments of 64 entries each. Below 128 a cache is a single
segment, and it evicts in one exact global least-recently-used order.
 
From 128 up, each segment evicts on its own. The capacity is divided
across the segments, and each segment evicts its own least recently
used entry when its own share is full. So the cache has the capacity
that the caller asked for, and clrucache_capacity() reports exactly
that number, but the entry picked to make room is the oldest inside
one segment and not the oldest of the whole cache. A hash spreads the
keys, so at any instant some segments are fuller than others, and a
cache that is full to exactly its capacity holds a little less than
that number. The shortfall is a few percent: Up to about ten below
roughly a thousand entries, around two at eight thousand entries and
above, and less as the cache grows. It depends neither on the key type
nor on the width of the build. The segment of a key comes from the
keyed hash of chashmap, which a secret of the process keys whatever
hash mode the map of each segment is in, so the shortfall for one set
of keys differs from one process to the next. The map of each segment
starts in the fast hash mode and switches to the keyed mode on its own
when the keys that reach it collide; see chashmap_create_full(3).
Benchmark your configuration against the access pattern you intend
instead of assuming either behaviour.
 
The eviction callback is called while the lock of the owning segment
is held, so it must not enter the cache again. Only the lock of that
one segment is held, so two evictions in different segments run the
callback at the same time on two threads, and any state the callback
keeps of its own needs its own protection.
ccache_destroy() waits until every in-flight resolved use of the handle
has stopped before it frees anything. Such a use is a concurrent
clrucache_get_full(), clrucache_set_full(), clrucache_size() or
clrucache_capacity() call, so the caller doesn't have to prove on its
own that no other thread is still using the cache. A destroy of a
handle that a call already destroyed, whether in an earlier call or on
another thread racing this one, is a FATAL ERROR: It calls abort() and
raises SIGABRT, and it is never a silent double-free.

ccache_construct(3), ccache_init(3), ccache_destroy(3), clrucache_get_full(3), clrucache_set_full(3), ccol_determine_ccol_data_type(3)