2017-03-21 09:58:58 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* machinarium.
|
|
|
|
*
|
|
|
|
* cooperative multitasking engine.
|
|
|
|
*/
|
|
|
|
|
2017-03-21 12:55:23 +00:00
|
|
|
#include <machinarium_private.h>
|
|
|
|
#include <machinarium.h>
|
2017-03-21 09:58:58 +00:00
|
|
|
|
2017-05-16 11:50:45 +00:00
|
|
|
#include <ucontext.h>
|
|
|
|
|
2017-03-21 09:58:58 +00:00
|
|
|
typedef struct mm_context_t mm_context_t;
|
|
|
|
|
|
|
|
struct mm_context_t {
|
2017-05-16 11:50:45 +00:00
|
|
|
ucontext_t context;
|
2017-03-21 09:58:58 +00:00
|
|
|
};
|
|
|
|
|
2017-05-16 12:07:55 +00:00
|
|
|
void *mm_context_alloc(void)
|
2017-03-21 09:58:58 +00:00
|
|
|
{
|
|
|
|
mm_context_t *ctx = malloc(sizeof(mm_context_t));
|
|
|
|
if (ctx == NULL)
|
|
|
|
return NULL;
|
2017-05-16 11:50:45 +00:00
|
|
|
memset(ctx, 0, sizeof(mm_context_t));
|
2017-03-21 09:58:58 +00:00
|
|
|
return ctx;
|
|
|
|
}
|
|
|
|
|
|
|
|
void mm_context_free(void *ctxp)
|
|
|
|
{
|
|
|
|
mm_context_t *ctx = ctxp;
|
|
|
|
free(ctx);
|
|
|
|
}
|
|
|
|
|
2017-05-16 12:07:55 +00:00
|
|
|
void
|
|
|
|
mm_context_create(void *ctxp, void *link, mm_fiberstack_t *stack,
|
|
|
|
void (*function)(void*),
|
|
|
|
void *arg)
|
2017-03-21 09:58:58 +00:00
|
|
|
{
|
2017-05-16 11:50:45 +00:00
|
|
|
mm_context_t *main_context = link;
|
2017-03-21 09:58:58 +00:00
|
|
|
mm_context_t *ctx = ctxp;
|
2017-05-16 12:07:55 +00:00
|
|
|
ctx->context.uc_stack.ss_sp = stack->pointer;
|
|
|
|
ctx->context.uc_stack.ss_size = stack->size;
|
2017-05-16 11:50:45 +00:00
|
|
|
ctx->context.uc_link = &main_context->context;
|
|
|
|
getcontext(&ctx->context);
|
|
|
|
makecontext(&ctx->context, (void(*)())function, 1, arg);
|
2017-03-21 09:58:58 +00:00
|
|
|
}
|
|
|
|
|
2017-05-16 12:07:55 +00:00
|
|
|
void
|
|
|
|
mm_context_swap(void *prevp, void *nextp)
|
2017-03-21 09:58:58 +00:00
|
|
|
{
|
|
|
|
mm_context_t *prev = prevp;
|
|
|
|
mm_context_t *next = nextp;
|
2017-05-16 11:50:45 +00:00
|
|
|
swapcontext(&prev->context, &next->context);
|
2017-03-21 09:58:58 +00:00
|
|
|
}
|