zoukankan      html  css  js  c++  java
  • 概念理解: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; }
  • 相关阅读:
    CF321B Solution
    CF722D Solution
    CF729E Solution
    CF1447E Solution
    CF962F Solution
    DropDownList绑定数据
    连接数据库
    jqm随记的东西
    正则表达式过滤超链接内容(.net)
    linq lambda操作list的例子
  • 原文地址:https://www.cnblogs.com/osbreak/p/10035807.html
Copyright © 2011-2022 走看看