/* * KPL Garbage Collector */ #pragma once /* * Per thread gc, additions and removals are done by the owner thread * Marking can be done by any thread */ typedef struct { _Atomic size_t gc_cycle_head_additions; // updated by owner thread, checked by any thread kpl_object_gc *gc_head, *gc_mark_head; // only can be accessed by owner thread } kpl_gc; /* * Init */ inline void kpl_gc_init(kpl_gc *gc) { __atomic_store_n(&gc->gc_cycle_head_additions, 0, __ATOMIC_RELAXED); gc->gc_head = gc->gc_mark_head = NULL; } /* * Create a new gc node and a new kpl_object with object_size * Add the node to the gc_head * Returns the new kpl_object, which has a pointer to the kpl_gc_object * Only owner thread calls this */ void *kpl_gc_new(kpl_thread *thread, kpl_interface *interface, int32_t object_size); /* * Delete an object on gc_head before sweeping * *object is the object the gc is tracking NOT a kpl_object_gc * Many objects can be removed from the gc before sweep and is done though this * *object is not void, force casting to prevent memory errors */ void kpl_gc_delete(kpl_thread *thread, kpl_object *object); /* * Mark a gc object * Tells gc not to delete object */ inline void kpl_gc_mark(kpl_object_gc *object_gc) { __atomic_test_and_set(&object_gc->gc_mark, __ATOMIC_SEQ_CST); } /* * Move gc_head to gc_mark head * Need task to traverse task and error queue to mark objects all call kpl_interface_gc_mark_object_fn * Has to be called separately from kpl_gc_sweep, other tasks will be running while gc runs */ inline void kpl_gc_prepare_sweep(kpl_gc *gc) { gc->gc_mark_head = gc->gc_head; gc->gc_head = NULL; gc->gc_cycle_head_additions = 0; } /* * Run sweep on unmarked objects on gc_mark_head * Clear mark on marked objects and return them to gc_head */ void kpl_gc_sweep(kpl_thread *thread); /* * Run delete on all objects on gc_head */ void kpl_gc_free(kpl_thread *thread);