#ifndef TRANS_H #define TRANS_H #include #include #include struct task { bool pending; char stack[SIGSTKSZ]; ucontext_t context; ucontext_t main_context; }; typedef void (*task_func) (struct task *t); static inline struct task * task_new (task_func func) { struct task *t; t = calloc (sizeof (struct task), 1); getcontext (&t->context); t->context.uc_link = 0; t->context.uc_stack.ss_sp = t->stack; t->context.uc_stack.ss_size = sizeof (t->stack); t->context.uc_stack.ss_flags = 0; makecontext (&t->context, (void (*)()) func, 1, t); swapcontext (&t->main_context, &t->context); return t; } static inline void task_free (struct task *t) { free (t); } static inline void task_yield (struct task *t) { t->pending = true; swapcontext (&t->context, &t->main_context); } static inline void task_complete (struct task *t) { t->pending = false; swapcontext (&t->context, &t->main_context); } static inline void task_handle (struct task *t) { if (t->pending) swapcontext (&t->main_context, &t->context); } #endif /* TRANS_H */