io_service相当于注册异步回调的一个上下文环境,而run相当于处理异步io的上下文(通常是一个线程)。
单io_service,多线程run,相当于多个线程同时来处理注册在一个io_service上的回调:
//sio_mth.cpp
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
using namespace boost::asio;
using namespace std;thread_local int t_id = 0;
unsigned long getTimestamp()
{return std::chrono::system_clock::now().time_since_epoch().count()/std::chrono::system_clock::period::den;
}void timer_handler(int timerID, const boost::system::error_code& err)
{if (err){cout << getTimestamp() << " Timer cancel" << endl;return;}cout << getTimestamp() <<" t_id:" << t_id << " timerID:" << timerID << " " << " Timer on"<<endl;if(t_id == 1){this_thread::sleep_for(1s);}else{this_thread::sleep_for(3s);}
}void threadRunIO(int id, io_service* ios)
{t_id = id;ios->run();
}int main()
{io_service ios;cout << getTimestamp() << " Timer enable" << endl;deadline_timer t1(ios, boost::posix_time::seconds(2));deadline_timer t2(ios, boost::posix_time::seconds(2));deadline_timer t3(ios, boost::posix_time::seconds(2));deadline_timer t4(ios, boost::posix_time::seconds(2));deadline_timer t5(ios, boost::posix_time::seconds(2));deadline_timer t6(ios, boost::posix_time::seconds(2));t1.async_wait(bind(timer_handler, 1, std::placeholders::_1));t2.async_wait(bind(timer_handler, 2, std::placeholders::_1));t3.async_wait(bind(timer_handler, 3, std::placeholders::_1));t4.async_wait(bind(timer_handler, 4, std::placeholders::_1));t5.async_wait(bind(timer_handler, 5, std::placeholders::_1));t6.async_wait(bind(timer_handler, 6, std::placeholders::_1));thread th1(threadRunIO, 1, &ios);thread th2(threadRunIO, 2, &ios);th1.join();th2.join();cout << getTimestamp() << " exit" << endl;return 0;
}//g++ -o sm sio_mth.cpp
启动了两个线程来运行同一个io_service上的异步处理。
两个线程会根据调度来处理:
1701936688 Timer enable
1701936690 t_id:2 timerID:1 Timer on
1701936690 t_id:1 timerID:2 Timer on
1701936691 t_id:1 timerID:3 Timer on
1701936692 t_id:1 timerID:4 Timer on
1701936693 t_id:2 timerID:5 Timer on
1701936693 t_id:1 timerID:6 Timer on
1701936696 exit可以看到线程2先处理了timerID:1
然后再次期间,线程1处理了timerID:2,timerID:3,timerID:4
之后线程2处理完了timerID:1后又开始处理timerID:5
线程1处理timerID:6
也就是会根据线程当前的忙闲情况,分配任务到线程