coroutines: get photonlib/coroutines working with GC

This commit is contained in:
Joe Conigliaro 2023-10-09 12:10:19 +11:00
parent 1f06476343
commit 9604a3f491
No known key found for this signature in database
GPG Key ID: C12F7136C08206F1
3 changed files with 22 additions and 2 deletions

View File

@ -24,8 +24,10 @@ int photon_init_default();
void photon_thread_create(void* (* f)(void*), void* arg); void photon_thread_create(void* (* f)(void*), void* arg);
void photon_sleep_s(int n); void photon_sleep_s(int n);
void photon_sleep_ms(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 #ifdef __cplusplus
} }

View File

@ -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_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_get_memory_use() usize
fn C.GC_add_roots(voidptr, voidptr)
fn C.GC_remove_roots(voidptr, voidptr)

View File

@ -14,6 +14,7 @@ fn C.photon_init_default() int
fn C.photon_thread_create(f voidptr, arg voidptr) fn C.photon_thread_create(f voidptr, arg voidptr)
fn C.photon_sleep_s(n int) fn C.photon_sleep_s(n int)
fn C.photon_sleep_ms(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() // sleep is coroutine-safe version of time.sleep()
pub fn sleep(duration time.Duration) { pub fn sleep(duration time.Duration) {
@ -21,6 +22,20 @@ pub fn sleep(duration time.Duration) {
} }
fn init() { 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() ret := C.photon_init_default()
if ret < 0 { if ret < 0 {
panic('failed to initialize coroutines via photon (ret=${ret})') panic('failed to initialize coroutines via photon (ret=${ret})')