summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/coroutines/cotasks2.c
blob: 293583bc85ad2150469f40e1037dc89c82c50afe (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// https://mariusbancila.ro/blog/2020/06/22/a-cpp20-coroutine-example/

#include <time.h>
#include <stdio.h>
#define i_static
#include <stc/cstr.h>
#include <stc/algo/coroutine.h>

cco_task_struct (next_value,
    int val;
    cco_timer tm;
);

int next_value(struct next_value* co, cco_runtime* rt)
{
    cco_routine (co) {
        while (true) {
            cco_timer_await(&co->tm, 1 + rand() % 2);
            co->val = rand();
            cco_yield();
        }
    }
    return 0;
}

void print_time()
{
    time_t now = time(NULL);
    char mbstr[64];
    strftime(mbstr, sizeof(mbstr), "[%H:%M:%S]", localtime(&now)); 
    printf("%s ", mbstr);
}

// PRODUCER

cco_task_struct (produce_items,
    struct next_value next;
    cstr str;
);

int produce_items(struct produce_items* p, cco_runtime* rt)
{
    cco_routine (p) {
        p->str = cstr_null;
        while (true)
        {
            // await for next CCO_YIELD in next_value()
            cco_await_task(&p->next, rt, CCO_YIELD);
            cstr_printf(&p->str, "item %d", p->next.val);
            print_time();
            printf("produced %s\n", cstr_str(&p->str));
            cco_yield();
        }
        cco_cleanup:
            cstr_drop(&p->str);
            puts("done produce");
    }
    return 0;
}

// CONSUMER

cco_task_struct (consume_items,
    int n, i;
    struct produce_items produce;
);

int consume_items(struct consume_items* c, cco_runtime* rt)
{
   cco_routine (c) {
        for (c->i = 1; c->i <= c->n; ++c->i)
        {
            printf("consume #%d\n", c->i);
            cco_await_task(&c->produce, rt, CCO_YIELD);
            print_time();
            printf("consumed %s\n", cstr_str(&c->produce.str));
        }
        cco_cleanup:
            cco_stop(&c->produce);
            cco_resume(&c->produce, rt);
            puts("done consume");
    }
    return 0;
}

int main(void)
{
    struct consume_items consume = {
        .n=5,
        .cco_fn=consume_items,
        .produce={.cco_fn=produce_items, .next={.cco_fn=next_value}},
    };
    int count = 0;

    cco_block_task(&consume)
    {
        ++count;
        //cco_sleep(0.001);
        //if (consume.i == 3)
        //    cco_stop(&consume);
    }
    printf("count: %d\n", count);
}