C 协同程序:Coroutine
jopen
10年前
Coroutine 是 C 的协同程序。
Coroutine 支持 32 位和 64 位模式,支持 Mac OS X 和 Linux。
构建:
./build.sh
API
struct coroutine; struct coroutine *coroutine_create(void (*func)(void *), void *arg); void coroutine_delete(struct coroutine *co); struct coroutine *coroutine_self(void); int coroutine_status(struct coroutine *co); void coroutine_resume(struct coroutine *co); void coroutine_yield(void); int coroutine_getstacksize(void); void coroutine_setstacksize(int size);
Example
这是包括在 coroutine/example/example.c 里面的:
#include <stdio.h> #include <stdlib.h> #include <coroutine.h> struct task { char buffer[1024]; }; void readline(void *arg) { struct coroutine *co = coroutine_self(); struct task *task = arg; while (1) { printf("[coroutine %p] read: ", co); if (fgets(task->buffer, sizeof(task->buffer), stdin) == NULL) break; coroutine_yield(); } } void echoline(void *arg) { struct coroutine *co = coroutine_self(); struct task *task = arg; while (1) { printf("[coroutine %p] echo: %s", co, task->buffer); coroutine_yield(); } } int main(int argc, char **argv) { struct task task; struct coroutine *coread = coroutine_create(readline, &task); struct coroutine *coecho = coroutine_create(echoline, &task); while (1) { coroutine_resume(coread); if (coroutine_status(coread) == COROUTINE_DEAD) break; coroutine_resume(coecho); } coroutine_delete(coread); coroutine_delete(coecho); return 0; }