C 协同程序:Coroutine
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; }
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!