summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/coroutines/scheduler.c
blob: 78461277a6998750226afdfdd73466c406a50fb8 (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
// https://www.youtube.com/watch?v=8sEe-4tig_A
#include <stdio.h>
#include <stc/coroutine.h>

struct Task {
    int (*fn)(struct Task*);
    int cco_state;
    struct Scheduler* sched;
};

#define i_type Scheduler
#define i_key struct Task
#include <stc/cqueue.h>

static bool schedule(Scheduler* sched)
{
    struct Task task = *Scheduler_front(sched);
    Scheduler_pop(sched);
    
    if (!cco_done(&task))
        task.fn(&task);
    
    return !Scheduler_empty(sched);
}

static int push_task(const struct Task* task)
{
    Scheduler_push(task->sched, *task);
    return CCO_YIELD;
}


static int taskA(struct Task* task)
{
    cco_routine(task) {
        puts("Hello, from task A");
        cco_yield_v(push_task(task));
        puts("A is back doing work");
        cco_yield_v(push_task(task));
        puts("A is back doing more work");
        cco_yield_v(push_task(task));
        puts("A is back doing even more work");
    }
    return 0;
}

static int taskB(struct Task* task) 
{
    cco_routine(task) {
        puts("Hello, from task B");
        cco_yield_v(push_task(task));
        puts("B is back doing work");
        cco_yield_v(push_task(task));
        puts("B is back doing more work");
    }
    return 0;
}

void Use(void)
{
    Scheduler scheduler = c_init(Scheduler, {
        {.fn=taskA, .sched=&scheduler}, 
        {.fn=taskB, .sched=&scheduler},
    });

    while (schedule(&scheduler)) {}

    Scheduler_drop(&scheduler);
}

int main(void)
{
    Use();
}