繁体   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