簡體   English   中英

我在使用 boost:asio 時是否偏執?

[英]Am I paranoid while using boost:asio?

我正在使用 boost:asio 編寫一個應用程序。

我有一個 io_serice::run() 線程和許多工作線程。 所有工作線程都可以隨時發送消息。

這是我實現send_msg()的方式。

// Note: send_msg() could be called from any thread.
// 'msg' must be 'malloc'ed, and its owner ship will be transfered  to '_send_q'
//
//  NetLibConnection has base classes of tcp::socket and  boost::enable_shared_from_this
void NetLibConnection::send_msg(PlainNetLibMsg*  msg)
{
    AutoLocker __dummy(this->_lock_4_send_q);    // _lock_4_send_q is a 'mutex'

    bool write_in_progress = ! this->_send_q.empty(); // _send_q is std::deque<PlainNetLibMsg* >, 
                                           // the 'send_q' mechansim is learned from  boost_asio_example/cpp03/chat  
    this->_send_q.push_back(msg);
    if (write_in_progress)
    {
        return;
    }

    this->get_io_service().post(      // queue the 'send operation' to a singlton io_serivce::run() thread

        boost::bind(&NetLibConnection::async_send_front_of_q
                , boost::dynamic_pointer_cast<NetLibConnection>(shared_from_this())
        ) 
    );
      
}

void NetLibConnection::async_send_front_of_q()
{
    boost::asio::async_write(*this 
        , boost::asio::buffer( this->_send_q.front() , _send_q.front()->header.DataSize + sizeof(NetLibChunkHeader) )
        , this->_strand.wrap(  // this great post   https://stackoverflow.com/questions/12794107/why-do-i-need-strand-per-connection-when-using-boostasio/
                              // convinced me that I should use strand along with  Connection
            boost::bind( &NetLibConnection::handle_send
                        , boost::dynamic_pointer_cast<NetLibConnection>(shared_from_this()) 
                        , boost::asio::placeholders::error
            )
        )
    );
}

代碼工作正常。 但我對它的冗長並不滿意。 我覺得senq_q的作用與strand相同。 自從

  1. 所有真正的async_write調用都發生在單個io_service::run()線程中
  2. 所有真正的async_write都通過send_q一個一個地排隊

我還需要strand嗎?

確實是的。 文檔在此處詳細說明了這一點:

線程和提升 Asio

通過僅從單個線程調用io_service::run() ,用戶的代碼可以避免與同步相關的開發復雜性。 例如,圖書館用戶可以實現單線程的可擴展服務器(從用戶的角度來看)。

從更廣泛的角度考慮,您的方案是具有單個邏輯鏈的最簡單形式。 還有其他方法可以維護邏輯鏈(通過鏈接處理程序),請參閱有關該主題的最出色的答案: 為什么在使用 boost::asio 時我需要每個連接的鏈?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM