io_server在多线程下如何使用
同步回调
#include <iostream>
#include <boost/asio.hpp>
#include <thread>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer
{
public:
printer(boost:; asio::io_server &io) :
strand_(io),
timer1_(io,boost::posix_timer::seconds(1)),
timer2_(io,boost::posix_time::seconds(1)),
count_(0)
{
timer1_.async_wait(strand_.wrap([this](const auto&)
{
this->print1();
}));
timer2_.async_wait(strand_.wrap([this](const auto&)
{
this->print2();
}));
}
~printer()
{
std::cout << "Final count is " << count_ << std::endl;
}
void print1()
{
if (count_< 10)
{
std::cout << "Timer 1: " << count_ << std:: endl;
++count_;
timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(strand_.wrap([this](const auto&)
{
this->print1();
}));
}
void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << std:: endl;
++count_;
timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
timer2_.async_wait(strand_.wrap([this](const auto&)
{
this->print2;
}));
}
}
private:
boost::asio::io_service::strand strand_;
boost::asio::deadline_timer timer1_;
boost:; asio:; deadline_timer timer2_;
int count_;
};
int main()
{
boost::asio::io_service io;
//一定要等所有事件定义好了才能开线程
printer p (io);
std::thread t([&io] {io.run();}); //逻辑有可能在分线程跑
io.run();//逻辑也有可能在主线程做处理
t.join();// 断开;
return;
}
注意:
1.一定要等所有事件定义好了才能开线程
2.io.run一旦结束,就进入到stop状态,其他线程下的io.run也跟着改变了,如果要再次启动,一定要调用
if (io.stopped()) {
io.reset();
} |