在 RPC 通信协议中,在调用方法后,我将“完成”消息发送回调用者。由于这些方法是以并发方式调用的,因此包含响应 (a std::string
) 的缓冲区需要由互斥锁保护。我想要达到的目标如下:
void connection::send_response()
{
// block until previous response is sent
std::unique_lock<std::mutex> locker(response_mutex_);
// prepare response
response_ = "foo";
// send response back to caller. move the unique_lock into the binder
// to keep the mutex locked until asio is done sending.
asio::async_write(stream_,
asio::const_buffers_1(response_.data(), response_.size()),
std::bind(&connection::response_sent, shared_from_this(),
_1, _2, std::move(locker))
);
}
void connection::response_sent(const boost::system::error_code& err, std::size_t len)
{
if (err) handle_error(err);
// the mutex is unlocked when the binder is destroyed
}
但是,这无法编译,因为boost::asio
要求处理程序是 CopyConstructible。
通过使用以下共享储物柜类而不是unique_lock
:
template <typename Mutex>
class shared_lock
{
public:
shared_lock(Mutex& m)
: p_(&m, std::mem_fn(&Mutex::unlock))
{ m.lock(); }
private:
std::shared_ptr<Mutex> p_;
};
boost::asio
不允许仅移动处理程序背后的原因是什么?