forked from edubart/minicoro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.c
More file actions
71 lines (60 loc) · 1.71 KB
/
example.c
File metadata and controls
71 lines (60 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#define MINICORO_IMPL
#include "minicoro.h"
#include <stdio.h>
static void fail(const char* message, mco_result res) {
printf("%s: %s\n", message, mco_result_description(res));
exit(-1);
}
static void fibonacci_coro(mco_coro* co) {
unsigned long m = 1;
unsigned long n = 1;
/* Retrieve max value. */
unsigned long max;
mco_result res = mco_pop(co, &max, sizeof(max));
if(res != MCO_SUCCESS)
fail("Failed to retrieve coroutine storage", res);
while(1) {
/* Yield the next Fibonacci number. */
mco_push(co, &m, sizeof(m));
res = mco_yield(co);
if(res != MCO_SUCCESS)
fail("Failed to yield coroutine", res);
unsigned long tmp = m + n;
m = n;
n = tmp;
if(m >= max)
break;
}
/* Yield the last Fibonacci number. */
mco_push(co, &m, sizeof(m));
}
int main() {
/* Create the coroutine. */
mco_coro* co;
mco_desc desc = mco_desc_init(fibonacci_coro, 0);
mco_result res = mco_create(&co, &desc);
if(res != MCO_SUCCESS)
fail("Failed to create coroutine", res);
/* Set storage. */
unsigned long max = 1000000000;
mco_push(co, &max, sizeof(max));
int counter = 1;
while(mco_status(co) == MCO_SUSPENDED) {
/* Resume the coroutine. */
res = mco_resume(co);
if(res != MCO_SUCCESS)
fail("Failed to resume coroutine", res);
/* Retrieve storage set in last coroutine yield. */
unsigned long ret = 0;
res = mco_pop(co, &ret, sizeof(ret));
if(res != MCO_SUCCESS)
fail("Failed to retrieve coroutine storage", res);
printf("fib %d = %lu\n", counter, ret);
counter = counter + 1;
}
/* Destroy the coroutine. */
res = mco_destroy(co);
if(res != MCO_SUCCESS)
fail("Failed to destroy coroutine", res);
return 0;
}