| 1 | /********** A really minimal coroutine package for C **********/ |
| 2 | #ifndef _STACKLET_H_ |
| 3 | #define _STACKLET_H_ |
| 4 | |
| 5 | #include "src/precommondefs.h" |
| 6 | #include <stdlib.h> |
| 7 | |
| 8 | |
| 9 | /* A "stacklet handle" is an opaque pointer to a suspended stack. |
| 10 | * Whenever we suspend the current stack in order to switch elsewhere, |
| 11 | * stacklet.c passes to the target a 'stacklet_handle' argument that points |
| 12 | * to the original stack now suspended. The handle must later be passed |
| 13 | * back to this API once, in order to resume the stack. It is only |
| 14 | * valid once. |
| 15 | */ |
| 16 | typedef struct stacklet_s *stacklet_handle; |
| 17 | |
| 18 | #define EMPTY_STACKLET_HANDLE ((stacklet_handle) -1) |
| 19 | |
| 20 | |
| 21 | /* Multithread support. |
| 22 | */ |
| 23 | typedef struct stacklet_thread_s *stacklet_thread_handle; |
| 24 | |
| 25 | RPY_EXTERN stacklet_thread_handle stacklet_newthread(void); |
| 26 | RPY_EXTERN void stacklet_deletethread(stacklet_thread_handle thrd); |
| 27 | |
| 28 | |
| 29 | /* The "run" function of a stacklet. The first argument is the handle |
| 30 | * of the stack from where we come. When such a function returns, it |
| 31 | * must return a (non-empty) stacklet_handle that tells where to go next. |
| 32 | */ |
| 33 | typedef stacklet_handle (*stacklet_run_fn)(stacklet_handle, void *); |
| 34 | |
| 35 | /* Call 'run(source, run_arg)' in a new stack. See stacklet_switch() |
| 36 | * for the return value. |
| 37 | */ |
| 38 | RPY_EXTERN stacklet_handle stacklet_new(stacklet_thread_handle thrd, |
| 39 | stacklet_run_fn run, void *run_arg); |
| 40 | |
| 41 | /* Switch to the target handle, resuming its stack. This returns: |
| 42 | * - if we come back from another call to stacklet_switch(), the source handle |
| 43 | * - if we come back from a run() that finishes, EMPTY_STACKLET_HANDLE |
| 44 | * - if we run out of memory, NULL |
| 45 | * Don't call this with an already-used target, with EMPTY_STACKLET_HANDLE, |
| 46 | * or with a stack handle from another thread (in multithreaded apps). |
| 47 | */ |
| 48 | RPY_EXTERN stacklet_handle stacklet_switch(stacklet_handle target); |
| 49 | |
| 50 | /* Delete a stack handle without resuming it at all. |
| 51 | * (This works even if the stack handle is of a different thread) |
| 52 | */ |
| 53 | RPY_EXTERN void stacklet_destroy(stacklet_handle target); |
| 54 | |
| 55 | /* stacklet_handle _stacklet_switch_to_copy(stacklet_handle) --- later */ |
| 56 | |
| 57 | /* Hack: translate a pointer into the stack of a stacklet into a pointer |
| 58 | * to where it is really stored so far. Only to access word-sized data. |
| 59 | */ |
| 60 | RPY_EXTERN |
| 61 | char **_stacklet_translate_pointer(stacklet_handle context, char **ptr); |
| 62 | |
| 63 | #endif /* _STACKLET_H_ */ |