• boost asio io_service 原理及与strand的比较


    io_service一般作为处理工作的work pool。

    网络中,作为服务器接收用,可以加速处理收到的信息。主要有post, dispatch, stop, run. 几可常用方法。通常还会用到boost bind一起使用

    io_service是并发的,在队列中,有几个run, 就有几个并发进行;而对于strand 是严格顺序进行的调用。

    看下面的例子:

    #include <iostream>
    #include <boost/shared_ptr.hpp>
    #include <boost/asio.hpp>
    #include <iostream>
    #include <boost/bind.hpp>
    #include <boost/thread/thread.hpp>
    #include <boost/thread/mutex.hpp>
    #include <boost/date_time/posix_time/posix_time.hpp>
    using namespace std;
    using namespace boost;
    using namespace asio;

    typedef boost::asio::io_service ioType;
    typedef boost::asio::strand strandType;
    ioType m_service;
    strandType m_strand(m_service);
    boost::mutex m_mutex;

    void print( int fatherID)
    {
      static int count = 0;
      cout<<"fatherID "<<fatherID<<" "<<endl;
      sleep(1);
      cout<<"count "<<count++<<endl;
    }

    void ioRun1()
    {
      while(1)    {      m_service.run();    }
    }

    void ioRun2()
    {
      while(1)    {      m_service.run();    }
    }

    void print1()
    {
      m_strand.dispatch(bind(print,1));
    }

    void print2()
    {
      m_strand.post(bind(print,2));
    }

    void print3()
    {
      m_strand.post(bind(print,3));
    }

    int main(void)
    {
      boost::thread t0(ioRun1);
      boost::thread t(ioRun2);
      boost::thread t1(print1);
      boost::thread t2(print2);
      boost::thread t3(print3);
      cout<<"231"<<endl;
      t1.join();
      t2.join();
      t3.join();
      t0.join();
      t.join();
      cout<<"24141"<<endl;
      return 0;
    }

    最终输出结果:

       fatherID 3
     count 0
     fatherID 2
     count 1

     fatherID 1
       count 2

    说明这是线程安全的!

    但是  而 io_service 不能保证!

    参考资料:http://sjtutmz.blog.163.com/blog/static/9888866020119145464870/

    世界如此的美好,江山如此的多娇! ---阳光正能量--->>>>>>>>>>>>>>>
  • 相关阅读:
    log4cxx在vs2013的静态编译
    windows下sqlite3静态库和动态库的编译
    iconv gbk字符转utf8字符
    wchar_t与char、wstring与string的相互转换
    获取当前时间并格式化
    快速获取文件大小
    cryptopp开源库的使用(二):base64加密
    cryptopp开源库的使用(零):windows下使用visual studio编译
    cryptopp开源库的使用(一):md5加密
    Docker 安装Oracle
  • 原文地址:https://www.cnblogs.com/upendi/p/2590304.html
Copyright © 2020-2023  润新知