boost::asio序列: 多线程

此博客通过示例展示了如何在Boost.Asio中使用多线程,并结合io_context::strand来控制执行顺序,确保了事件处理的线程安全。文章通过打印线程ID揭示了io_context::run()在不同线程中的运行特性,特别是超时事件Handler可能在主线程或额外创建的线程中执行。
摘要由CSDN通过智能技术生成

 示例代码中,在原来boost::asio代码基础上,增加了打印线程id的代码,方便理解多线程执行boost::asio::io_context::run()(或 boost::asio::io_service::run())的特点,同时,在这个示例中,学习boost::asio::io_context::strand的作用,就是,控制执行的顺序,先加入的先执行

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class printer
{
public:
  printer(boost::asio::io_context& io)
    : strand_(io),
      timer1_(io, boost::posix_time::seconds(1)),
      timer2_(io, boost::posix_time::seconds(1)),
      count_(0)
  {
    timer1_.async_wait(boost::asio::bind_executor(strand_,
          boost::bind(&printer::print1, this)));

    timer2_.async_wait(boost::asio::bind_executor(strand_,
          boost::bind(&printer::print2, this)));
  }

  ~printer()
  {
    std::cout << "Final count is " << count_ << std
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值