memory_arena
Loading...
Searching...
No Matches
arena_shrink_monitor.c

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:

This function is thread-safe and acquires the arena lock internally.

Parameters
arenaPointer 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 "arena.h"
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdatomic.h>
static atomic_bool keep_running = true;
void* shrink_monitor_thread(void* arg)
{
t_arena* arena = (t_arena*) arg;
while (atomic_load(&keep_running))
{
sleep(1); // Check every second
}
return NULL;
}
int main(void)
{
t_arena* arena = arena_create(1024, true); // Growable arena
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");
arena_delete(&arena);
return 1;
}
// Simulate allocations and deallocations
for (int i = 0; i < 10; ++i)
{
arena_alloc(arena, 1024 * 32); // allocate 32 KB
usleep(200 * 1000); // wait 200ms
arena_reset(arena); // simulate freeing all
}
// Stop background thread
atomic_store(&keep_running, false);
pthread_join(thread, NULL);
arena_delete(&arena);
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.