summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/cointerleave.c
diff options
context:
space:
mode:
authorTyge Løvset <[email protected]>2023-05-02 07:20:29 +0200
committerTyge Løvset <[email protected]>2023-05-02 07:20:29 +0200
commit2adea8b3b06ebe1b2152870862100f7e7985cfdf (patch)
tree7d37dc14784f33e9b40888253aa5c7183d81c6b0 /misc/examples/cointerleave.c
parent399eb8d0e1de2839d826a9e0cf123d90d00b0018 (diff)
downloadSTC-modified-2adea8b3b06ebe1b2152870862100f7e7985cfdf.tar.gz
STC-modified-2adea8b3b06ebe1b2152870862100f7e7985cfdf.zip
Improved coroutine.h, added new coro examples.
Diffstat (limited to 'misc/examples/cointerleave.c')
-rw-r--r--misc/examples/cointerleave.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/misc/examples/cointerleave.c b/misc/examples/cointerleave.c
new file mode 100644
index 00000000..64473d96
--- /dev/null
+++ b/misc/examples/cointerleave.c
@@ -0,0 +1,60 @@
+// https://www.youtube.com/watch?v=8sEe-4tig_A
+#include <stc/calgo.h>
+#include <stdio.h>
+#define i_type IVec
+#define i_val int
+#include <stc/cvec.h>
+
+struct GenValue {
+ IVec *v;
+ IVec_iter it;
+ int cco_state;
+};
+
+static int next_value(struct GenValue* g)
+{
+ cco_begin(g);
+ for (g->it = IVec_begin(g->v); g->it.ref; IVec_next(&g->it))
+ cco_yield(*g->it.ref);
+ cco_final:
+ cco_end(0);
+}
+
+struct Generator {
+ struct GenValue x, y;
+ int cco_state;
+ int value;
+};
+
+bool interleaved(struct Generator* g)
+{
+ cco_begin(g);
+ while (cco_alive(&g->x) || cco_alive(&g->y))
+ {
+ g->value = next_value(&g->x);
+ if (cco_alive(&g->x)) cco_yield(false);
+
+ g->value = next_value(&g->y);
+ if (cco_alive(&g->y)) cco_yield(false);
+ }
+ cco_final:
+ cco_end(true);
+}
+
+void Use(void)
+{
+ IVec a = c_make(IVec, {2, 4, 6, 8, 10, 11});
+ IVec b = c_make(IVec, {3, 5, 7, 9});
+
+ struct Generator g = {{&a}, {&b}};
+
+ while (!interleaved(&g))
+ printf("%d\n", g.value);
+
+ c_drop(IVec, &a, &b);
+}
+
+int main()
+{
+ Use();
+}