|
| 1 | +#define LIBCO_C |
| 2 | +#include "libco.h" |
| 3 | + |
| 4 | +#define _BSD_SOURCE |
| 5 | +#define _XOPEN_SOURCE 500 |
| 6 | +#include <stdlib.h> |
| 7 | +#include <emscripten/fiber.h> |
| 8 | +#include <stdio.h> |
| 9 | + |
| 10 | +#ifdef __cplusplus |
| 11 | +extern "C" { |
| 12 | +#endif |
| 13 | + |
| 14 | +typedef void (*thread_cb)(); |
| 15 | + |
| 16 | +// Todo: dynamic stack size |
| 17 | +typedef struct { |
| 18 | + emscripten_fiber_t context; |
| 19 | + char *asyncify_stack; |
| 20 | + char *c_stack; |
| 21 | +} Fiber; |
| 22 | + |
| 23 | +static inline void thread_entry(void *entrypoint) { |
| 24 | + ((thread_cb)entrypoint)(); |
| 25 | +} |
| 26 | + |
| 27 | +static Fiber main_fiber; |
| 28 | +static Fiber* running_fiber = 0; |
| 29 | + |
| 30 | +void init_main_fiber() { |
| 31 | + main_fiber.asyncify_stack = (char*)malloc(16385 * sizeof(char)); |
| 32 | + emscripten_fiber_init_from_current_context(&main_fiber.context, main_fiber.asyncify_stack, 16385); |
| 33 | + running_fiber = &main_fiber; |
| 34 | +} |
| 35 | + |
| 36 | +cothread_t co_active() { |
| 37 | + if(!running_fiber) init_main_fiber(); |
| 38 | + |
| 39 | + return (cothread_t)running_fiber; |
| 40 | +} |
| 41 | + |
| 42 | +cothread_t co_derive(void* memory, unsigned int heapsize, void (*coentry)(void)) { |
| 43 | + if(!running_fiber) init_main_fiber(); |
| 44 | + |
| 45 | + Fiber* fiber = malloc(sizeof(Fiber)); |
| 46 | + fiber->c_stack = (char*) memory; |
| 47 | + fiber->asyncify_stack = (char*) malloc(heapsize * sizeof(char)); |
| 48 | + |
| 49 | + emscripten_fiber_init(&fiber->context, thread_entry, coentry, fiber->c_stack, heapsize, fiber->asyncify_stack, heapsize); |
| 50 | + |
| 51 | + return (cothread_t)fiber; |
| 52 | +} |
| 53 | + |
| 54 | +cothread_t co_create(unsigned int heapsize, void (*coentry)(void)) { |
| 55 | + if(!running_fiber) init_main_fiber(); |
| 56 | + |
| 57 | + Fiber* fiber = malloc(sizeof(Fiber)); |
| 58 | + fiber->c_stack = (char*)malloc(heapsize * sizeof(char)); |
| 59 | + fiber->asyncify_stack = (char*)malloc(heapsize * sizeof(char)); |
| 60 | + |
| 61 | + emscripten_fiber_init(&fiber->context, thread_entry, coentry, fiber->c_stack, heapsize, fiber->asyncify_stack, heapsize); |
| 62 | + |
| 63 | + return (cothread_t)fiber; |
| 64 | +} |
| 65 | + |
| 66 | +void co_delete(cothread_t cothread) { |
| 67 | + if(cothread) { |
| 68 | + free(cothread); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +void co_switch(cothread_t cothread) { |
| 73 | + Fiber* old_fiber = running_fiber; |
| 74 | + running_fiber = (Fiber*)cothread; |
| 75 | + |
| 76 | + emscripten_fiber_swap(&old_fiber->context, &running_fiber->context); |
| 77 | +} |
| 78 | + |
| 79 | +int co_serializable() { |
| 80 | + return 0; |
| 81 | +} |
| 82 | + |
| 83 | +#ifdef __cplusplus |
| 84 | +} |
| 85 | +#endif |
0 commit comments