LeviLamina
Loading...
Searching...
No Matches
TickSyncSleep.h
1#pragma once
2
3#include <atomic>
4#include <condition_variable>
5#include <cstddef>
6#include <functional>
7#include <mutex>
8#include <optional>
9#include <utility>
10#include <vector>
11
12#include "ll/api/base/Macro.h"
13#include "ll/api/chrono/GameChrono.h"
14
15namespace ll::thread {
16
18 struct Impl;
19 std::unique_ptr<Impl> impl;
20
21protected:
22 LLAPI std::unique_lock<std::mutex> lock();
23
24 LLAPI void sleepImpl(std::unique_lock<std::mutex>&);
25 LLAPI void interruptImpl();
26
27 virtual void check() = 0;
28
29public:
31 TickSyncSleepBase(TickSyncSleepBase const&) = delete;
32 TickSyncSleepBase& operator=(TickSyncSleepBase&&) = delete;
33 TickSyncSleepBase& operator=(TickSyncSleepBase const&) = delete;
34
35 LLAPI TickSyncSleepBase();
36 LLAPI virtual ~TickSyncSleepBase();
37};
38
39template <class Clock>
41 void check() override {
42 if (!timepoint) return;
43 if (Clock::now() >= *timepoint) {
44 interrupt();
45 }
46 }
47
48public:
49 using clock_type = Clock;
50
51 std::optional<typename Clock::time_point> timepoint;
52
53 TickSyncSleep() = default;
54 virtual ~TickSyncSleep() = default;
55
56 void sleepFor(Clock::duration duration) {
57 std::unique_lock l{lock()};
58 timepoint = Clock::now() + duration;
59 sleepImpl(l);
60 }
61
62 void sleepUntil(Clock::time_point time) {
63 std::unique_lock l{lock()};
64 timepoint = time;
65 sleepImpl(l);
66 }
67
68 void sleep() {
69 std::unique_lock l{lock()};
70 timepoint = std::nullopt;
71 sleepImpl(l);
72 }
73
74 void interrupt() {
75 std::unique_lock l{lock()};
76 timepoint = std::nullopt;
77 interruptImpl();
78 }
79};
80} // namespace ll::thread
Definition TickSyncSleep.h:17
Definition TickSyncSleep.h:40