summaryrefslogtreecommitdiff
path: root/async/time_scheduler.h
blob: e09de16ce0d9fb88a6460d648987009dccab98b3 (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
#pragma once

#include <chrono>

#include "scheduler.h"

template <typename Duration = std::chrono::milliseconds>
struct time_scheduler_t {
    struct wakeup_future : public schedulable {
        time_scheduler_t& tsched;
        Duration time;
        wakeup_future(time_scheduler_t& tsched, Duration time) : tsched(tsched), time(time) {}

        bool await_ready() {
            return tsched.now >= time;
        }

        bool await_suspend(std::coroutine_handle<> h) {
            if(tsched.now >= time) {
                return false;
            } else {
                awaiter = h;
                tsched.push_wakeup(this);
                return true;
            }
        }

        void await_resume() {}

        void resume() {
            scheduler.schedule(*this);
        }
    };

    Duration now;

    wakeup_future* wakeup_queue;

    void push_wakeup(wakeup_future* fut) {
        wakeup_future** p = &wakeup_queue;

        while((*p) && (*p)->time <= fut->time) {
            p = reinterpret_cast<wakeup_future**>(&(*p)->next);
        }

        fut->next = *p;
        *p = fut;
    }

    async_flag tick_flag;

    void tick() {
        tick_flag.set();
    }

    task wakeup_task() {
        while(1) {
            co_await tick_flag;
            now++;

            while(wakeup_queue && wakeup_queue->time <= now) {
                auto fut = wakeup_queue;
                wakeup_queue = static_cast<wakeup_future*>(fut->next);
                fut->resume();
            }
        }
    }

    wakeup_future sleep_until(Duration time) {
        return {*this, time};
    }

    wakeup_future sleep(Duration duration) {
        return sleep_until(now + duration);
    }
};