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

Posted osbreak

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了概念理解:boost::asio::定时器2相关的知识,希望对你有一定的参考价值。

 

多线程同步回调
#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的主要内容,如果未能解决你的问题,请参考以下文章

C++ Boost ASIO 简单的周期性定时器?

boost asio 学习 定时器

从 boost::threads 到 boost::asio 定时器

Boost Asio总结(10)定时器

Boost asio 截止时间计时器立即完成(C++)

Boost ASIO TCP计时器客户端错误“解决:找不到指定的类”