Skip to content

Instantly share code, notes, and snippets.

@felipec
Created September 28, 2008 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipec/13493 to your computer and use it in GitHub Desktop.
Save felipec/13493 to your computer and use it in GitHub Desktop.
continuation task test
#ifndef TRANS_H
#define TRANS_H
#include <ucontext.h>
#include <stdbool.h>
#include <stdio.h>
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 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment