用c语言简单模拟协程
看了云风的http://blog.codingnow.com/2012/07/c_coroutine.html,他实现了一个简单的协程调度。
我这里仅仅是用c语言模拟了协程,原理很简单。
主要是:
getcontext()
makecontext()
swapcontext()
这几个函数。具体api详解见http://pubs.opengroup.org/onlinepubs/009695399/functions/makecontext.html
#ifndef _CORO_H #define _COEO_H #include <ucontext.h> typedef void (*coro_func)(void *); typedef struct coro_context { ucontext_t context; coro_func func; void *argv; char *sptr; size_t ssize; }coro_context_t; coro_context_t* coro_create(coro_func coro,void *arg,void *sptr,size_t ssize); void coro_transfer (coro_context_t *prev, coro_context_t *next); void coro_destroy (coro_context_t *ctx); #endif
#include"coro.h" #include <stdlib.h> coro_context_t* coro_create(coro_func func,void *arg,void *sptr,size_t ssize) { coro_context_t *ctx = (coro_context_t*)malloc(sizeof(coro_context_t)); getcontext(&ctx->context); ctx->context.uc_link = 0; ctx->context.uc_stack.ss_sp = sptr; ctx->context.uc_stack.ss_size = ssize; ctx->context.uc_stack.ss_flags = 0; makecontext(&ctx->context, (void (*)(void)) func, 1, arg); return ctx; } void coro_transfer (coro_context_t *prev, coro_context_t *next) { swapcontext(&prev->context, &next->context); } void coro_destroy (coro_context_t *ctx) { free(ctx); }
#include"coro.h" #include<stdio.h> coro_context_t *coro1; coro_context_t *maincoro; char stack1[1024*16]; char stack2[1024*16]; void test1(void *argv) { printf("test\n"); } int main(){ coro1 = coro_create(test1,NULL,stack1,1024*8); maincoro = coro_create(NULL,NULL,stack2,1024*8); while(1){ coro_transfer(maincoro,coro1); printf("main\n"); } coro_destroy(coro1); coro_destroy(maincoro); }