Boost:asio多io_service,多线程run
多io_service,多线程run,相当于多个线程分别处理注册在不同io_service上的回调,也就是每个线程排某个io_service的异步处理:
//mio_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(2s);
}
cout << getTimestamp() <<" t_id:" << t_id << " timerID:" << timerID << " " << " Timer done"<<endl;
}
void threadRunIO(int id, io_service* ios)
{
t_id = id;
ios->run();
cout << getTimestamp() <<" t_id:" << t_id << " exit" << endl;
}
int main()
{
io_service ios1, ios2;
cout << getTimestamp() << " Timer enable" << endl;
deadline_timer t1(ios1, boost::posix_time::seconds(2));
deadline_timer t2(ios1, boost::posix_time::seconds(2));
deadline_timer t3(ios1, boost::posix_time::seconds(2));
deadline_timer t4(ios1, boost::posix_time::seconds(2));
deadline_timer t5(ios1, boost::posix_time::seconds(2));
deadline_timer t6(ios2, 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, &ios1);
thread th2(threadRunIO, 2, &ios2);
th1.join();
th2.join();
cout << getTimestamp() << " exit" << endl;
return 0;
}
//g++ -o mm mio_mth.cpp
运行程序输出:
1701937582 Timer enable
1701937584 t_id:1 timerID:1 Timer on
1701937584 t_id:2 timerID:6 Timer on
1701937585 t_id:1 timerID:1 Timer done
1701937585 t_id:1 timerID:2 Timer on
1701937586 t_id:2 timerID:6 Timer done
1701937586 t_id:2 exit
1701937586 t_id:1 timerID:2 Timer done
1701937586 t_id:1 timerID:3 Timer on
1701937587 t_id:1 timerID:3 Timer done
1701937587 t_id:1 timerID:4 Timer on
1701937588 t_id:1 timerID:4 Timer done
1701937588 t_id:1 timerID:5 Timer on
1701937589 t_id:1 timerID:5 Timer done
1701937589 t_id:1 exit
1701937589 exit可以看到线程2处理timerID:6,与此同时线程1处理timerID:1和timerID:2
然后当线程2处理完timerID:6后,由于没有其他注册在ios2上的回调了,即使他空闲下来了,也不会处理其他timerID,因此线程2会先退出
因为其他的timerID都注册在了ios1上,所以只能等待线程1依次处理。