diff options
Diffstat (limited to 'misc/examples/coroutines/scheduler.c')
| -rw-r--r-- | misc/examples/coroutines/scheduler.c | 73 |
1 files changed, 33 insertions, 40 deletions
diff --git a/misc/examples/coroutines/scheduler.c b/misc/examples/coroutines/scheduler.c index 78461277..be1810d2 100644 --- a/misc/examples/coroutines/scheduler.c +++ b/misc/examples/coroutines/scheduler.c @@ -2,70 +2,63 @@ #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 +#define i_type cco_tasks +#define i_key cco_task* +#define i_keydrop(x) { puts("free task"); free(*x); } +#define i_no_clone #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); -} +typedef struct { + cco_tasks tasks; +} cco_scheduler; -static int push_task(const struct Task* task) -{ - Scheduler_push(task->sched, *task); - return CCO_YIELD; +void cco_scheduler_drop(cco_scheduler* sched) { + cco_tasks_drop(&sched->tasks); } +int cco_scheduler_run(cco_scheduler* sched) { + while (!cco_tasks_empty(&sched->tasks)) { + cco_task* task = cco_tasks_pull(&sched->tasks); + if (cco_resume_task(task, NULL)) + cco_tasks_push(&sched->tasks, task); + else + cco_tasks_value_drop(&task); + } + return 0; +} -static int taskA(struct Task* task) -{ +static int taskA(cco_task* task, cco_runtime* rt) { cco_routine(task) { puts("Hello, from task A"); - cco_yield_v(push_task(task)); + cco_yield(); puts("A is back doing work"); - cco_yield_v(push_task(task)); + cco_yield(); puts("A is back doing more work"); - cco_yield_v(push_task(task)); + cco_yield(); puts("A is back doing even more work"); } return 0; } -static int taskB(struct Task* task) -{ +static int taskB(cco_task* task, cco_runtime* rt) { cco_routine(task) { puts("Hello, from task B"); - cco_yield_v(push_task(task)); + cco_yield(); puts("B is back doing work"); - cco_yield_v(push_task(task)); + cco_yield(); 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)) {} +void Use(void) { + cco_scheduler sched = {.tasks = c_init(cco_tasks, { + c_new(cco_task, {.cco_func=taskA}), + c_new(cco_task, {.cco_func=taskB}), + })}; - Scheduler_drop(&scheduler); + cco_scheduler_run(&sched); + cco_scheduler_drop(&sched); } int main(void) |
