14、boost asio 教程---计时器

让我们暂时离开多线程执行模型,学习一些非常简单的东西。在处理I/O的几乎任何应用程序中都需要的工具是计时器。因此,让我们学习如何在Boost.Asio中使用它们。

有四种提供的计时器:

boost::asio::deadline_timer
boost::asio::high_resolution_timer
boost::asio::steady_timer
boost::asio::system_timer

然而,它们都提供相同的功能。它们之间的区别在于deadline_timer基于boost::posix_time,而其他计时器基于std::chrono计时器。因此,没有真正需要详细讨论它们,因为它们提供相同的接口和行为类型。让我们看一下high_resolution_timer的用法示例。

#include <boost/asio.hpp>
#include <iostream>

namespace io = boost::asio;
using error_code = boost::system::error_code;

io::io_context io_context;

// 从io_context引用构造计时器
io::high_resolution_timer timer(io_context);

auto now()
{
    return std::chrono::high_resolution_clock::now();
}

auto begin = now();

void async_wait()
{
    // 设置到期持续时间
    timer.expires_after(std::chrono::seconds(1));

    // 异步等待到期
    timer.async_wait([&] (error_code error)
    {
      

猜你喜欢

转载自blog.csdn.net/Knowledgebase/article/details/132984732