【发布时间】:2013-10-04 23:03:19
【问题描述】:
我有一个简单的异步服务器,灵感来自boost asio documentation(单线程服务器)中的 HTTP 服务器示例,它处理客户端发送的请求。
每当新客户端连接并调用其start() 方法(如HTTP 服务器示例中所示)时,我的server 类都会创建一个新的connection 对象。 connection 实例读取客户端的请求,然后使用异步操作(即boost::asio::async_read 和boost::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