Boost :: asio :: write上的互斥体不起作用 [英] mutex on boost::asio::write not works

查看:79
本文介绍了Boost :: asio :: write上的互斥体不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make an async tcp client(it's gonna not waits for result of a request before sending another request).

请求方法如下:

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像这样:

write method calls boost::asio::write like this:

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);
}

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

But looks like still multiple threads do write concurrently as what I receive in server is like:

{键":"Val {"键":值}; ue};

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

我该怎么办?

推荐答案

您确实对写入asio 设置了锁定保护.如您所见,无法保证另一端将使用相同的保护程序对其进行处理.

You did put the lock guard around writing to the asio. There is, as you can see, no guarantee the other end will have them processed with the same guard.

您宁愿在asio中编写json 时将警卫放置在需要的地方:

You should rather put the guard where you need it, on writing the json, out of the 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.

这篇关于Boost :: asio :: write上的互斥体不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆