Attempt to shrink the arena's buffer if underutilized.
Attempt to shrink the arena's buffer if underutilized.This function evaluates whether the current memory usage of the arena is significantly lower than its allocated size. If so, and if the arena allows dynamic resizing, it attempts to shrink the buffer to reduce memory footprint.
The shrink target is computed as the current used size plus a padding (ARENA_SHRINK_PADDING) to avoid immediate re-expansion.
Conditions for shrinking:
arena != NULL
can_grow is true
- The usage ratio (
offset / size) is below ARENA_MIN_SHRINK_RATIO
- The computed target size is smaller than the current buffer size
This function is thread-safe and acquires the arena lock internally.
- Parameters
-
| arena | Pointer to the arena to check for shrinking opportunity. |
- Note
- This is a non-destructive optimization. It has no effect if the arena does not support resizing, is already compact, or if shrinking would not release significant memory.
- See also
- arena_shrink
-
arena_should_maybe_shrink
-
arena_shrink_target
Example of running a background thread to monitor and shrink an arena.
This example creates a shared arena that is used for allocations, while a background thread periodically checks whether the arena should be shrunk using arena_might_shrink().
This pattern is useful in applications that experience temporary spikes in memory usage but want to reclaim memory afterward without destroying the arena.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdatomic.h>
static atomic_bool keep_running = true;
void* shrink_monitor_thread(void* arg)
{
while (atomic_load(&keep_running))
{
sleep(1);
}
return NULL;
}
int main(void)
{
if (!arena)
{
fprintf(stderr, "Failed to create arena.\n");
return 1;
}
pthread_t thread;
if (pthread_create(&thread, NULL, shrink_monitor_thread, arena) != 0)
{
fprintf(stderr, "Failed to create shrink monitor thread.\n");
return 1;
}
for (int i = 0; i < 10; ++i)
{
usleep(200 * 1000);
}
atomic_store(&keep_running, false);
pthread_join(thread, NULL);
return 0;
}
Core public API for the Arena memory allocator.
void arena_reset(t_arena *arena)
void * arena_alloc(t_arena *arena, size_t size)
bool arena_might_shrink(t_arena *arena)
void arena_delete(t_arena **arena)
t_arena * arena_create(size_t size, bool allow_grow)
The main memory arena structure used for fast allocation.