boost::asio::write 上的互斥锁不起作用

mutex on boost::asio::write not works

我正在尝试制作一个异步 tcp 客户端(它不会在发送另一个请求之前等待请求的结果)。

请求方法如下所示:

std::future<void> AsyncClient::SomeRequestMethod(sometype& parameter)
{
    return std::async(
        std::launch::async,
        [&]()
        {
            // Gonna send a json. ';' at the end of a json separates the requests.
            const std::string requestJson = Serializer::ArraySumRequest(numbers) + ';';
            boost::system::error_code err;

            write(requestJson, err);
            // Other stuff.

write 方法调用 boost::asio::write 像这样:

void AsyncClient::write(const std::string& strToWrite, boost::system::error_code& err)
{
    // m_writeMutex is a class member I use to synchronize writing.
    std::lock_guard<std::mutex> lock(m_writeMutex);
    boost::asio::write(m_socket,
        boost::asio::buffer(strToWrite), err);
}

但看起来仍然有多个线程并发写入,因为我在服务器中收到的是这样的:

{"Key":"Val{"Key":Value};ue"};

我该怎么办?

您确实在 写入 asio 时设置了锁保护。如您所见,无法保证另一端会使用相同的守卫处理它们。

你应该把守卫放在你需要的地方,在写 json 时,在 asio 之外:

void AsyncClient::write(const std::string& strToWrite, boost::system::error_code& err)
{
    // m_writeMutex is a class member I use to synchronize writing.
//  std::lock_guard<std::mutex> lock(m_writeMutex);
    boost::asio::write(m_socket,
    boost::asio::buffer(strToWrite), err);
}

return std::async(
    std::launch::async,
    [&]()
    {
        std::lock_guard<std::mutex> lock(m_writeMutex); // <--- here

        // Gonna send a json. ';' at the end of a json separates the requests.
        const std::string requestJson = Serializer::ArraySumRequest(numbers) + ';';
        boost::system::error_code err;

        write(requestJson, err);
        // Other stuff.