2014-03-19 108 views
0

在助力asio教程timer5。我不知道兩個`io_service.run()`的功能是什麼?

boost::thread t(boost::bind(&boost::asio::io_service::run, &io));在main函數中的作用。

我們爲什麼要調用兩個io_serice.run()

// 
// timer.cpp 
// ~~~~~~~~~ 
// 
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) 
// 
// Distributed under the Boost Software License, Version 1.0. (See accompanying 
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 
// 

#include <iostream> 
#include <boost/asio.hpp> 
#include <boost/thread/thread.hpp> 
#include <boost/bind.hpp> 
#include <boost/date_time/posix_time/posix_time.hpp> 

class printer 
{ 
public: 
    printer(boost::asio::io_service& io) 
    : strand_(io), 
     timer1_(io, boost::posix_time::seconds(1)), 
     timer2_(io, boost::posix_time::seconds(1)), 
     count_(0) 
    { 
    timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this))); 
    timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this))); 
    } 

    ~printer() 
    { 
    std::cout << "Final count is " << count_ << "\n"; 
    } 

    void print1() 
    { 
    if (count_ < 10) 
    { 
     std::cout << "Timer 1: " << count_ << "\n"; 
     ++count_; 

     timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1)); 
     timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this))); 
    } 
    } 

    void print2() 
    { 
    if (count_ < 10) 
    { 
     std::cout << "Timer 2: " << count_ << "\n"; 
     ++count_; 

     timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1)); 
     timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this))); 
    } 
    } 

private: 
    boost::asio::strand strand_; 
    boost::asio::deadline_timer timer1_; 
    boost::asio::deadline_timer timer2_; 
    int count_; 
}; 

int main() 
{ 
    boost::asio::io_service io; 
    printer p(io); 
    boost::thread t(boost::bind(&boost::asio::io_service::run, &io)); 
    io.run(); 
    t.join(); 

    return 0; 
} 

回答

0

也就是說例子展示瞭如何使用一個線程池(在這種情況下,通過兩個線程組成)。如果您希望同時執行多個異步處理程序,則可能需要一個池。

報你的鏈接頁面:

如果你發現自己陷入這些侷限,另一種方法是讓線程調用io_service對象池:: run()的

要提交一個線程到asio線程池,在該線程上執行io_service::run。這個例子提交了兩個線程:boost :: thread t和主線程。

+0

它使用2個線程來演示該鏈確保handler1和hander2一個接一個地執行,但同時執行。如果我們使用一個線程,無論我們使用「strand」還是不使用,處理器都一定會被逐個執行。 – Sam

0

本教程演示瞭如何通過讓線程池調用io_service::run()來併發執行處理程序。然而,本教程通過調用兩個異步調用鏈,通過相同的strand來證明這一點,在處理程序中保證不會同時運行。

儘管如此,文件建議有線程調用io_service::run()如果應用經驗池:

  • 當解毒可能需要很長的時間才能完成差的響應。
  • 無法在多處理器系統上進行擴展。