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; }
  • 相关阅读:
    C#面向对象的三大特性概述
    SQL Server 低版本还原高版本的数据库
    将表转化成脚本的存储过程
    iis安装失败解决方法
    kafka consumer 配置详解
    C#解析XML文件
    blat
    REST接口POST方法发送文件到服务器(C#)
    http://www.codeproject.com/Questions/117324/uploadfileincwithHttpWebRequest
    PDF Password Remover
  • 原文地址:https://www.cnblogs.com/osbreak/p/10035807.html
Copyright © 2011-2022 走看看