From 9604a3f491a08ea1576b4722212b83c6a6a8d2a4 Mon Sep 17 00:00:00 2001 From: Joe Conigliaro Date: Mon, 9 Oct 2023 12:10:19 +1100 Subject: [PATCH] coroutines: get photonlib/coroutines working with GC --- thirdparty/photon/photonwrapper.h | 6 ++++-- vlib/builtin/builtin_d_gcboehm.c.v | 3 +++ vlib/coroutines/coroutines.v | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/thirdparty/photon/photonwrapper.h b/thirdparty/photon/photonwrapper.h index 76123c6aa527f4..97833b01e38f1e 100644 --- a/thirdparty/photon/photonwrapper.h +++ b/thirdparty/photon/photonwrapper.h @@ -24,8 +24,10 @@ int photon_init_default(); void photon_thread_create(void* (* f)(void*), void* arg); void photon_sleep_s(int n); void photon_sleep_ms(int n); - - +void set_photon_thread_stack_allocator( + void* (*alloc_func)(void*, size_t), + void (*dealloc_func)(void*, void*, size_t) +); #ifdef __cplusplus } diff --git a/vlib/builtin/builtin_d_gcboehm.c.v b/vlib/builtin/builtin_d_gcboehm.c.v index a2ff9efc484e32..9be092a57d4d92 100644 --- a/vlib/builtin/builtin_d_gcboehm.c.v +++ b/vlib/builtin/builtin_d_gcboehm.c.v @@ -139,3 +139,6 @@ pub fn gc_check_leaks() { fn C.GC_get_heap_usage_safe(pheap_size &usize, pfree_bytes &usize, punmapped_bytes &usize, pbytes_since_gc &usize, ptotal_bytes &usize) fn C.GC_get_memory_use() usize + +fn C.GC_add_roots(voidptr, voidptr) +fn C.GC_remove_roots(voidptr, voidptr) diff --git a/vlib/coroutines/coroutines.v b/vlib/coroutines/coroutines.v index 0d50ad3a039612..98a79a39fece71 100644 --- a/vlib/coroutines/coroutines.v +++ b/vlib/coroutines/coroutines.v @@ -14,6 +14,7 @@ fn C.photon_init_default() int fn C.photon_thread_create(f voidptr, arg voidptr) fn C.photon_sleep_s(n int) fn C.photon_sleep_ms(n int) +fn C.set_photon_thread_stack_allocator(fn (voidptr, int) voidptr, fn (voidptr, voidptr, int)) // sleep is coroutine-safe version of time.sleep() pub fn sleep(duration time.Duration) { @@ -21,6 +22,20 @@ pub fn sleep(duration time.Duration) { } fn init() { + alloc := fn (_ voidptr, stack_size int) voidptr { + unsafe { + stack_ptr := malloc(stack_size) + C.GC_add_roots(stack_ptr, charptr(stack_ptr) + stack_size) + return stack_ptr + } + } + dealloc := fn (_ voidptr, stack_ptr voidptr, stack_size int) { + unsafe { + C.GC_add_roots(stack_ptr, charptr(stack_ptr) + stack_size) + free(stack_ptr) + } + } + C.set_photon_thread_stack_allocator(alloc, dealloc) ret := C.photon_init_default() if ret < 0 { panic('failed to initialize coroutines via photon (ret=${ret})')