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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM