Skip to content

Commit

Permalink
coroutines: get photonlib/coroutines working with GC
Browse files Browse the repository at this point in the history
  • Loading branch information
joe-conigliaro committed Oct 9, 2023
1 parent 1f06476 commit 9604a3f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
6 changes: 4 additions & 2 deletions thirdparty/photon/photonwrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions vlib/builtin/builtin_d_gcboehm.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -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)
15 changes: 15 additions & 0 deletions vlib/coroutines/coroutines.v
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,28 @@ 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) {
C.photon_sleep_ms(duration.milliseconds())
}

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)

This comment has been minimized.

Copy link
@lihuiba

lihuiba Oct 10, 2023

should it be something like GC_remove_root?

This comment has been minimized.

Copy link
@medvednikov

medvednikov Oct 10, 2023

Member

Yes @lihuiba, it was fixed in the next commit :)

This comment has been minimized.

Copy link
@joe-conigliaro

joe-conigliaro Oct 10, 2023

Author Member

Indeed you are correct :) I corrected it in the next commit, thanks!

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})')
Expand Down

0 comments on commit 9604a3f

Please sign in to comment.