码迷,mamicode.com
首页 > 其他好文 > 详细

概念理解:boost::asio::定时器2

时间:2018-11-29 01:36:05      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:amp   namespace   pac   class   wait   col   posix   timer   bind   

 

多线程同步回调
#include <cstdio> #include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/asio/strand.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace boost; using namespace std; class CPrinter { public: CPrinter(boost::asio::io_service &io) :m_strand(io) , m_timer1(io, boost::posix_time::seconds(5)) , m_timer2(io, boost::posix_time::seconds(5)) , m_count(0) { m_timer1.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print1, this))); m_timer2.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print2, this))); } ~CPrinter() { cout << "m_count = " << m_count << endl; } void Print1() { if (m_count < 10) { cout << "Timer1 count = " << m_count << endl; cout << boost::this_thread::get_id() << endl; m_count++; m_timer1.expires_at(m_timer1.expires_at() + boost::posix_time::seconds(1)); m_timer1.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print1, this))); } } void Print2() { if (m_count < 10) { cout << "Timer2 count = " << m_count << endl; cout << boost::this_thread::get_id() << endl; m_count++; m_timer2.expires_at(m_timer2.expires_at() + boost::posix_time::seconds(1)); m_timer2.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print2, this))); } } private: //strand提供串行执行, 能够保证线程安全, 同时被post或dispatch的方法, 不会被并发 boost::asio::strand m_strand; boost::asio::deadline_timer m_timer1; boost::asio::deadline_timer m_timer2; int m_count; }; int main() { cout << boost::this_thread::get_id() << endl; boost::asio::io_service io; CPrinter cp(io); cout << "to run" << endl; boost::thread td(boost::bind(&boost::asio::io_service::run, &io)); io.run(); cout << "exit" << endl; return EXIT_SUCCESS; }

 

概念理解:boost::asio::定时器2

标签:amp   namespace   pac   class   wait   col   posix   timer   bind   

原文地址:https://www.cnblogs.com/osbreak/p/10035807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!