【问题标题】:Execute computational taks in boost asio asynchronous server在 boost asio 异步服务器中执行计算任务
【发布时间】:2013-10-04 23:03:19
【问题描述】:

我有一个简单的异步服务器,灵感来自boost asio documentation(单线程服务器)中的 HTTP 服务器示例,它处理客户端发送的请求。

每当新客户端连接并调用其start() 方法(如HTTP 服务器示例中所示)时,我的server 类都会创建一个新的connection 对象。 connection 实例读取客户端的请求,然后使用异步操作(即boost::asio::async_readboost::asio::async_write)发送回复

这是connection 类的简化版本:

void connection::start() {
    // Read request from a client
    boost::asio::mutable_buffers_1 read_buffer = boost::asio::buffer(
            buffer_data_, REQUET_SIZE);
    boost::asio::async_read(socket_, read_buffer,
            boost::bind(&connection::handle_read_request, shared_from_this(),
                    read_buffer, boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred));
}

// Error handling omitted for the sake of brievty
void connection::handle_read_request(boost::asio::mutable_buffers_1& buffer,
    const boost::system::error_code& e, std::size_t bytes_transferred) {
      request req = parse_request(buffer);
      if(req.type_ = REQUEST_TYPE_1) {
          reply rep(...........);
          rep.prepare_buffer(buffer_data_.c_array());
          // Send the request using async_write
          boost::asio::async_write(socket_,
               boost::asio::buffer(buffer_data_, rep.required_buffer_size()),
               boost::bind(&connection::stop, shared_from_this()));
      } else if(req.type_ = REQUEST_TYPE_2 {
          // Need to do heavy computational task
      }
}

所有这些都非常有效,但是,在某些情况下,我需要执行繁重的计算任务 (REQUEST_TYPE_2)。我无法在handle_read_request 中执行这些任务,因为它们会阻塞单线程服务器并阻止其他客户端开始提供服务。

理想情况下,我想将繁重的计算任务提交到线程池,并在任务完成后运行我的连接类的方法(例如connection::handle_done_task(std::string computation_result))。这个handle_done_task(std::string computation_result) 会将计算结果发送给客户端(使用boost::asio::async_write)。

我该怎么做?是否有一些我应该注意的问题(从多个线程在同一个套接字上调用 boost::asio::async_write 是否安全)?

【问题讨论】:

    标签: c++ multithreading boost-asio


    【解决方案1】:

    正如文档明确指出的那样,asio 对象(strand/io_service 除外)不是线程安全的,因此您不应在没有同步的情况下从多个线程调用 async_write。相反,使用 post-to-io_service 习惯用法。像这样:

    // pseudocode, untested!
    if (req.type_ = REQUEST_TYPE_2) 
    {
      auto self = shared_from_this(); // lets capture shared_ptr<connection> to ensure its lifespan
      auto handler = [=](computation_result_type res)
      {
        // post the function that accesses asio i/o objects to `io_service` thread
        self->io_->post([] { handle_done_task(res); });
      }
    
      thread worker([=](const std::function<(computation_result_type res)> &handler) 
      {     
        // do the heavy work...
        // then invoke the handler
        handler(result);
      });
      worker.detach();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 2015-08-07
      相关资源
      最近更新 更多