I was trying to learn more about C++ 20 coroutines. After trying to read the documentation and watching few videos, I tried to write a timer that uses coroutines.
#include <coroutine>
#include <thread>
#include <chrono>
#include <utility>
#include <iostream>
struct Timer
{
struct promise_type
{
std::chrono::seconds m_wait_for_seconds;
void unhandled_exception() noexcept
{
}
std::suspend_never initial_suspend() noexcept
{
return {};
}
std::suspend_always final_suspend() noexcept
{
return {};
}
std::suspend_always await_transform(std::chrono::seconds value)
{
m_wait_for_seconds = value;
return {};
}
Timer get_return_object()
{
return Timer{*this};
}
};
using handle_type = std::coroutine_handle<promise_type>;
handle_type handle;
explicit Timer(promise_type& promise)
: handle(handle_type::from_promise(promise))
{
}
Timer(Timer&& other)
: handle(std::exchange(other.handle, nullptr))
{
}
~Timer()
{
if (handle)
{
handle.destroy();
}
}
void start()
{
if (!handle.done())
{
std::jthread t([this] {
std::this_thread::sleep_for(handle.promise().m_wait_for_seconds);
std::cout << "After waiting for " << handle.promise().m_wait_for_seconds.count() << " seconds\n";
});
}
}
};
Timer start_timer(std::chrono::seconds value)
{
co_await value;
}
int main()
{
Timer timer{start_timer(std::chrono::seconds(2))};
timer.start();
}
This code seems to work fine. Are there any ways to improve this?