BRICKS
Small, useful blocks of code, to build bigger things.
Loading...
Searching...
No Matches
timer.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <chrono>
4#include <future>
5#include <thread>
6
7namespace bricks {
8
21class timer {
22 public:
24 timer() noexcept {}; // NOLINT (can't use default, since std::promise does not have a noexcept
25 // ctor)
26
28 timer(const timer&) = delete;
30 auto operator=(const timer&) -> timer& = delete;
31
33 timer(timer&&) = default;
35 auto operator=(timer&&) -> timer& = default;
36
43 ~timer() { abort(); };
44
56 using completion_token = std::future<void>;
57
69 template <typename Rep = int64_t, typename Period = std::ratio<1>>
70 [[nodiscard]] auto start(const std::chrono::duration<Rep, Period>& duration =
71 std::chrono::duration<Rep, Period>{}) const noexcept
73 {
74 return std::async(std::launch::async, [abortion_future = abortion_future_, duration]() {
75 abortion_future.wait_for(duration);
76 });
77 }
78
87 inline auto abort() -> void
88 {
89 abortion_promise_.set_value();
90 abortion_promise_ = {};
91 abortion_future_ = abortion_promise_.get_future();
92 }
93
94 private:
95 std::promise<void> abortion_promise_{};
96 std::shared_future<void> abortion_future_{abortion_promise_.get_future()};
97};
98
99} // namespace bricks
A timer that can be started and aborted.
Definition timer.hpp:21
auto operator=(const timer &) -> timer &=delete
A timer cannot be copied.
~timer()
Destroy the timer object.
Definition timer.hpp:43
auto operator=(timer &&) -> timer &=default
Move assignment operator.
timer(const timer &)=delete
A timer cannot be copied.
timer() noexcept
Default constructor.
Definition timer.hpp:24
auto start(const std::chrono::duration< Rep, Period > &duration=std::chrono::duration< Rep, Period >{}) const noexcept -> completion_token
Starts the timer, returning a completion token that will be completed when the timer expires.
Definition timer.hpp:70
timer(timer &&)=default
Move constructor.
std::future< void > completion_token
A completion token that can be used to wait for the timer to complete.
Definition timer.hpp:56
auto abort() -> void
Aborts the timer.
Definition timer.hpp:87
Definition algorithm.hpp:12