Such home-based memory management is useful when a lot of memory blocks are allocated for given task. The allocations are done via the memory home, which keeps a reference to each block. When the memory home is then freed, it will free all blocks to which it has reference.
Typically, there is a home object which contains a su_home_t structure in the beginning of the object (sort of inheritance from su_home_t):
struct context { su_home_t ctx_home[1]; other_t *ctx_stuff; ... }
A new home memory pool can be created with su_home_new():
struct context *ctx = su_home_new(sizeof (struct context));
It is also possible to create a secondary memory pool that can be released separately:
struct context *ctx = su_home_clone(tophome, sizeof (struct context));
Note that the tophome has a reference to ctx structure; whenever tophome is freed, the ctx is also freed.
You can also create an independent home object by passing NULL as tophome argument. This is identical to the call to su_home_new().
The memory allocations using ctx proceed then as follows:
zeroblock = su_zalloc(ctx->ctx_home, sizeof (*zeroblock));
The home memory pool - the home object and all the memory blocks allocated using it - are freed when su_home_unref() is called:
su_home_unref(ctx->ctx_home).
su_free(tophome, ctx);
int example(su_home_t *home, ...) { su_home_t temphome[1] = { SU_HOME_INIT(temphome) }; ... do lot of allocations with temphome ... if (success) su_home_move(home, temphome); su_home_deinit(temphome); return success; }
Note that the temphome is deinitialized in every case, but when operation is successful, the allocations are moved from temphome to home.
threadsafe
by calling su_home_threadsafe() with the home pointer as argument. The threadsafeness is not inherited by clones.The threadsafe home objects can be locked and unlocked with su_home_mutex_lock() and su_home_mutex_unlock().
The word auto refers to the automatic scope; however, the home object initialized with su_home_auto() must be explicitly deinitialized with su_home_deinit() when the program exits the scope where the stack frame used in su_home_auto() was allocate.
Files | |
file | su_alloc.c |
Home-based memory management. | |
file | su_alloc_lock.c |
Thread-locking for su_alloc module. | |
file | su_sprintf.c |
su_*sprintf() functions | |
file | su_strdup.c |
Home-based string duplication functions. | |
file | su_alloc.h |
Home-based memory management interface. | |
file | su_alloc_stat.h |
Home-based memory management statistics. |