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 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!