使用底层的操作系统定时器(例如Windows API的SetTimer函数)代替asio::steady_timer,然后使用co_await在协程中等待操作完成。以下是示例代码:
#include
using namespace std; using namespace std::experimental;
class TimerAwaitable { public: TimerAwaitable() { timer_id_ = SetTimer(NULL, 0, 1000, &TimerAwaitable::timer_callback_); // 如果使用boost.asio,可以将SetTimer换成asio::steady_timer // timer_.expires_after(chrono::seconds(1)); // timer_.async_wait(TimerAwaitable::timer_callback_); } ~TimerAwaitable() { KillTimer(NULL, timer_id_); // 如果使用boost.asio,可以使用timer_.cancel() } bool await_ready() const { return false; } void await_suspend(coroutine_handle<> hdl) const { coro_handle_ = hdl; } void await_resume() const {
}
static VOID CALLBACK timer_callback_(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
coro_handle_.resume();
}
private: UINT_PTR timer_id_; static coroutine_handle<> coro_handle_; };
coroutine_handle<> TimerAwaitable::coro_handle_ = nullptr;
int main() { auto timer_awaitable = TimerAwaitable(); for (int i = 0; i < 5; ++i) { co_await timer_awaitable; cout << "tick" << endl; } return 0; }