C语言简单协程实现

1.运行效果

2.程序代码


#include <stdio.h>

typedef struct{
        void*           arg;
        void            (*yield_init)(void *);
        void            (*yield_alter)(void *);
        int             index;
        int             count;
        int             state;
}wlib_yield_t;
typedef  void (*yield_func_t)(void *);

#define wlib_yield_begin(state)             switch(state){ case 0:
#define wlib_yield_return(state, ret)       (state) = __LINE__; return (ret); case __LINE__:
#define wlib_yield_end()                    }

void count_init(void* n)
{
    *((int*)n) = 1;
}

void count_task(void* n)
{
    *((int*)n) += *((int*)n);
}

void wlib_yield_init(wlib_yield_t* yield,int count,void* arg,yield_func_t init,yield_func_t alter)
{
    yield->state = 0;
    yield->count = count;
    yield->arg = arg;
    yield->yield_init = init;
    yield->yield_alter = alter;
}

void* wlib_yield(wlib_yield_t* py)
{
    wlib_yield_begin(py->state);
    for(;;)
    {
        //if(NULL != py->yield_init)
        py->yield_init(py->arg);
        for(py->index = 0; py->index < py->count; py->index++)
        {
            wlib_yield_return(py->state, py->arg);
            py->yield_alter(py->arg);
        }
    }
    wlib_yield_end();
}

int main()
{
    wlib_yield_t t;
    int a;
    //t.state = 0;
    //t.count = 20;
    //t.arg = &a;
    //t.yield_init = count_init;
    //t.yield_alter = count_task;
    wlib_yield_init(&t,10,&a,count_init,count_task);
    int i;
    for(i = 0; i < 20; i++)
    {
        printf("%d ", *((int*)wlib_yield(&t)));
    }
    return 0;
}