boost::asio 序列5: io_context

本文探讨了boost::asio中的io_context核心组件,包括如何使用run_one_until()进行任务调度,io_context::executor_type在任务提交中的作用,以及io_context::work防止无任务时run()的提前退出。此外,还介绍了io_context::service作为服务基类,以及initiate_dispatch和initiate_post用于提交任务。最后,强调了detail::io_context_impl在异步调度中的关键角色,实现了run()等相关功能。
摘要由CSDN通过智能技术生成

io_context 

run()

(1)当全部异步操作完成或调用stop()时结束

(2)  阻塞线程

run_one()

(1)当全部异步操作完成或调用stop()时结束

(2)  阻塞线程

(3) 至多执行一个异步任务

run_for()

(1) 当全部异步操作完成或调用stop()或等待超时

(2) 阻塞线程

run_until()

(1) 当全部异步操作完成或调用stop()或到达指定时间点

(2) 阻塞线程

run_one_for()

(1)当全部异步操作完成或调用stop()时结束或等待超时

(2)  阻塞线程

(3) 至多执行一个异步任务

run_one_until()

(1)当全部异步操作完成或调用stop()时结束或到达指定时间点

(2)  阻塞线程

poll()

(1) 执行io_context对象的事件循环执行就绪的handlers,

(2) 当无就绪的handler或调用stop()时非阻塞退出

(3) 非阻塞线程

简而言之,有就绪handler需要执行,就执行,否则立刻退出

poll_one()

(1) 执行io_context对象的事件循环执行至多一个就绪的handlers

(2) 当无就绪的handler或调用stop()时非阻塞退出

(3) 非阻塞线程

简而言之,有就绪handler需要执行,就执行,否则立刻退出

stop() 终止io_context的全部异步操作
restart() 当run(), run_one(), poll() 或 poll_one() 返回之后(例如调用stop()或无更多异步操作),需要重新调用restart()函数。
reset() 废弃,类似restart()
dispatch(Handler) 请求io_context执行对应的handler,阻塞线程
pose(Handler) 请求io_context执行对应的handler, 非阻塞线程
warp(Handler)  创建新的Handler,并自动调用dispatch(Handler)

executor_type get_executor()

获取关联的执行器(executor) ,其中 executor_type为内部类

在实际调度过程中,实际都是调用run_one_until(),如下代码: 

template <typename Rep, typename Period>
std::size_t io_context::run_for(
    const chrono::duration<Rep, Period>& rel_time)
{
  return this->run_until(chrono::steady_clock::now() + rel_time);
}

template <typename Clock, typename Duration>
std::size_t io_context::run_until(
    const chrono::time_point<Clock, Duration>& abs_time)
{
  std::size_t n = 0;
  while (this->run_one_until(abs_time))
    if (n != (std::numeric_limits<std::size_t>::max)())
      ++n;
  return n;
}

template <typename Rep, typename Period>
std::size_t io_context::run_one_for(
    const chrono::duration<Rep, Period>& rel_time)
{
  return this->run_one_until(chrono::steady_clock::now() + rel_time);
}

template <typename Clock, typename Durat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值