summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/scheduler.c
blob: bad5201b0772d6533c64b876a5bd5d1080ce14d7 (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/calgo.h>

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

#define i_type Scheduler
#define i_val struct Task
#define i_no_cmp
#include <stc/clist.h>

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

static bool push_task(const struct Task* task)
{
    Scheduler_push_back(task->sched, *task);
    return false;
}


static bool taskA(struct Task* task)
{
    cco_begin(task);
        puts("Hello, from task A");
        cco_yield(push_task(task));
        puts("A is back doing work");
        cco_yield(push_task(task));
        puts("A is back doing more work");
        cco_yield(push_task(task));
        puts("A is back doing even more work");
    cco_end(true);
}

static bool taskB(struct Task* task) 
{
    cco_begin(task);
        puts("Hello, from task B");
        cco_yield(push_task(task));
        puts("B is back doing work");
        cco_yield(push_task(task));
        puts("B is back doing more work");
    cco_end(true);
}

void Use(void)
{
    Scheduler scheduler = c_make(Scheduler, {
        {taskA, &scheduler}, 
        {taskB, &scheduler},
    });

    while (schedule(&scheduler)) {}

    Scheduler_drop(&scheduler);
}

int main()
{
    Use();
}