gpt4 book ai didi

c++ - boost::asio::basic_waitable_timer 自定义时钟

转载 作者:行者123 更新时间:2023-11-28 04:29:13 28 4
gpt4 key购买 nike

我想创建一个可以手动设置并与 boost::asio::basic_waitable_timer

一起使用的自定义时钟

我尝试了以下方法:

class my_clock {
public:
using duration = std::chrono::nanoseconds;
using time_point = std::chrono::time_point<std::chrono::system_clock>;
static time_point now() {
return n;
}
static void set_now(time_point now) {
n = now;
}
private:
static time_point n;

};
my_clock::time_point my_clock::n = my_clock::time_point();

然后按以下方式使用它:

boost::asio::io_context ctx;
auto now = std::chrono::system_clock::now();
my_clock::set_now(now);
auto next_expire = now + std::chrono::milliseconds(10);
boost::asio::basic_waitable_timer<my_clock> ctimer(ctx);
ctimer.expires_at(next_expire);

int count = 0;
ctimer.async_wait([&](const boost::asio::error_code& ec) {
count++;
});
ctx.run_one();
// count == 0
my_clock::set_now(next_expire + std::chrono::seconds(1));
ctx.run();
// count == 1, except it's NOT

关于如何以这种方式将自定义时钟注入(inject) basic_waitiable_timer 有什么建议吗?

最佳答案

在@sergiopm 的回复的帮助下,以下是一个可行的解决方案:

class my_clock {
public:
using duration = std::chrono::nanoseconds;
using time_point = std::chrono::time_point<my_clock>;
using rep = duration::rep;
using period = duration::period;
static constexpr bool is_steady = false;

static time_point now() noexcept {
return n;
}
static void set_now(time_point now) {
n = now;
}
private:
static time_point n;
};

然后您需要覆盖 waitable_timer 的等待特性,以便它在轮询 io 上下文时不会等待挂钟:

struct wait_traits
{
static typename my_clock::duration to_wait_duration(
const typename my_clock::duration& d)
{
return std::chrono::nanoseconds(0);
}
};

然后按如下方式练习:

asio::io_context ctx;
auto now = my_clock::time_point(my_clock::duration(10));
my_clock::set_now(now);
asio::basic_waitable_timer<my_clock, wait_traits> ctimer(ctx);
auto next_expire = now + std::chrono::milliseconds(10);
ctimer.expires_at(next_expire);
ctimer.async_wait([&](const asio::error_code& ec) {
future_period_count++;
std::cout << "THIS HAPPENED" << std::endl;
});
ctx.poll_one();
REQUIRE(future_period_count == 0);
my_clock::set_now(next_expire + std::chrono::seconds(1));
ctx.run_one();
REQUIRE(future_period_count == 1);

关于c++ - boost::asio::basic_waitable_timer 自定义时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com