Cogo
Asymmetric stackless coroutine library for C/C++.
Install / Use
/learn @moxitrel/CogoREADME
-
Introduction An asymmetric stackless coroutine library written in pure C for embedded programming inspired by Protothreads, which implemented yield, await, concurrency and channel.
-
Advantages compared with other stackful coroutine libraries
- better portability
- unlimited recursion (avoid stack overflow) for coroutine
-
Difference compared with Protothreads
-
Overview #+BEGIN_SRC C #include "cogo/cogo_paral.h"
CO_DECLARE(coroutine_name, T parameter, ...) { CO_BEGIN:
//
// User codes.
//
CO_END:; } #+END_SRC
- Example *** Natural number generator #+BEGIN_SRC C #include <stdio.h> #include "cogo/cogo.h"
// Define generator. CO_DECLARE(nat, int n) { nat_t* thiz = (nat_t*)COGO_THIS; CO_BEGIN:
for (thiz->n = 0;; thiz->n++) { CO_YIELD; // return (next call start from here) }
CO_END:; }
// Usage. void example(void) { nat_t ng = COGO_INIT(&ng, nat, /n/ 0);
COGO_RESUME(&ng); printf("ng.n: %d\n", ng.n); // ng.n: 0
COGO_RESUME(&ng); printf("ng.n: %d\n", ng.n); // ng.n: 1
COGO_RESUME(&ng); printf("ng.n: %d\n", ng.n); // ng.n: 2 } #+END_SRC
- See Also
- [[https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html][Coroutines in C]]
- [[http://dunkels.com/adam/pt/][Protothreads]]
