[Boost] ASIO學習筆記:post and dispatch

posted in: ASIO, boost, C/C++程式設計 | 0

對於io_service之中,最重要的莫過於post跟dispatch這二個功能。到底這二個功能有何異同呢?

post:指的是將一個工作加入Completion Event Queue裡面
dispatch:若是在被run()或poll()所回呼的handler,則馬上執行指派的工作,若是在main()的線程中,則效力與post相同。

試著執行以下程式可以看到二個函式的不同:

boost::mutex global_stream_lock;

void Dispatch( int x ){   
    global_stream_lock.lock();  
    std::cout < < "[" <<  boost::this_thread::get_id()  << "] "  
        << __FUNCTION__  << " x = " << x <<  std::endl;     
    global_stream_lock.unlock();
}
void Post( int x ){ 
        global_stream_lock.lock();       
        std::cout << "[" <<  boost::this_thread::get_id()  << "] "     
            << __FUNCTION__  << " x = " << x <<  std::endl;      
        global_stream_lock.unlock();
}
void Run( boost::shared_ptr< boost::asio::io_service > io_service ){   

    for( int x = 0; x < 3; ++x )        {        
        io_service->post( boost::bind( &Post, x * 2 + 1 ) );   
        io_service->dispatch( boost::bind( &Dispatch, x * 2 ) );  
    }
}


int main( int argc, char * argv[] ){   
    boost::shared_ptr< boost::asio::io_service > io_service( new boost::asio::io_service);
    boost::shared_ptr< boost::asio::io_service::work > work( new boost::asio::io_service::work( *io_service )); 
    io_service->dispatch( boost::bind( &Dispatch,1111) ); 
    io_service->post( boost::bind( &Run, io_service ) );  
    io_service->post( boost::bind( &Post, 2222) ); 
    io_service->dispatch( boost::bind( &Dispatch, 3333) ); 
    io_service->poll();

    io_service->dispatch( boost::bind( &Dispatch,4444) ); 
    io_service->post( boost::bind( &Run, io_service ) );  
    io_service->post( boost::bind( &Post, 5555) );     
    io_service->dispatch( boost::bind( &Dispatch, 6666) ); 
    io_service->stop();
    io_service->poll();
    system("pause");
    return 0;
}


在們執行io_service->stop()之後,由於run()是透過io_service所回呼的,因此雖然dispatch可以在當下馬上就執行成功,但是原本被post到Completion Event Queue中的post function卻不會執行。另外,我們也可以看到在main()中所執行的post跟dispatch我們可以看到其實並沒有什麼差異性。

Leave a Reply

Your email address will not be published. Required fields are marked *