示例代码中,在原来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