【问题标题】:mutex on boost::asio::write not worksboost::asio::write 上的互斥锁不起作用
【发布时间】:2021-01-14 10:12:40
【问题描述】:

我正在尝试创建一个异步 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"};

我该怎么办?

【问题讨论】:

    标签: c++ sockets asynchronous boost-asio race-condition


    【解决方案1】:

    您确实在写信给 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.
    

    【讨论】:

    • 为此苦苦挣扎了 2 天。谢谢。
    猜你喜欢
    • 2011-07-22
    • 2013-01-30
    • 2022-06-13
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多