diff options
| author | nodist <kevin.comas.git@gmail.com> | 2026-11-01 10:07:03 -0500 |
|---|---|---|
| committer | nodist <kevin.comas.git@gmail.com> | 2026-11-01 10:07:03 -0500 |
| commit | 9a61168aec3373be702bdbf252043ce3605f2b5b (patch) | |
| tree | 49078373733f1eb4294569cede513aa7f82b94f0 /include/kpl/gc.h | |
| parent | fcc5294b919856ff04fef859760d48d0da136396 (diff) | |
add basic gc test
Diffstat (limited to 'include/kpl/gc.h')
| -rw-r--r-- | include/kpl/gc.h | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/include/kpl/gc.h b/include/kpl/gc.h new file mode 100644 index 0000000..074ba49 --- /dev/null +++ b/include/kpl/gc.h @@ -0,0 +1,73 @@ +/* + * 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_gc_object + * Only owner thread calls this + */ +kpl_object_gc *kpl_gc_new(kpl_thread *thread, kpl_interface *interface, int32_t object_size); + +/* + * Remove node from gc_head + * Free gc node and the object it wraps + * Only owner thread call this during sweep or free + */ +void kpl_gc_delete(kpl_thread *thread, kpl_object_gc *object_gc); + +/* + * 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 + */ +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 + */ +inline void kpl_gc_free(kpl_gc *gc, kpl_thread *thread) { + kpl_object_gc *head = gc->gc_head; + while (head) { + kpl_object_gc *tmp = head; + head = head->gc_next; + kpl_gc_delete(thread, tmp); + } +} |
