sample from  https://gist.github.com/felipec/13493

#ifndef TRANS_H
#define TRANS_H

#include <ucontext.h>

#include <stdbool.h>
#include <stdio.h>

struct task
{
    bool pending;
    char stack[SIGSTKSZ];
int  icnt ; 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); }

static inline void
task_inc_icnt(struct task *t)
{
    ++t->icnt ;
}

static inline int
task_print_icnt(struct task *t)
{
    return t->icnt ;
}

#endif /* TRANS_H */

===================================================

#include "task.h"

void func(struct task* t)
{
    int idx ;
    printf("inside func \n") ;
    for(idx=0;idx<5;idx++)
    {
        printf("(%d)....\n",idx) ;
        task_inc_icnt(t) ;
        task_yield(t) ;
    }
    task_complete(t) ;
}

int main (int argc, char *argv[])
{
    task_func f = &func ;
    struct task* t  ;
    t = task_new(f) ;
    printf("after task_new \n") ;
    int idx ;
    for(idx=0;idx<10;idx++)
    {
        printf("in main \n") ;
        task_handle(t) ;
    }
    printf("icnt=(%d)\n",task_print_icnt(t)) ;
    task_free(t) ;
    printf("end \n") ;
}

=====================================================

inside func
(0)....
after task_new
in main
(1)....
in main
(2)....
in main
(3)....
in main
(4)....
in main
in main
in main
in main
in main
in main
icnt=(4)
end

 

Quite easy , right ?!

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()