【问题标题】:Getting "the requested resource is in use" when using asio::async_write in single thread在单线程中使用 asio::async_write 时获取“请求的资源正在使用中”
【发布时间】:2017-11-13 11:24:09
【问题描述】:

这是我的代码。

boost::asio::async_write(*serialPort, boost::asio::buffer(*something),handler);
boost::asio::async_write(*serialPort, boost::asio::buffer(*something2),handler);

上面的代码会在第二行得到一个错误“请求的资源正在使用中”(注意异步流是一个串口)。但是当我将流更改为 tcp 套接字时,一切正常。为什么?

现在我知道我不能用这些组合的异步操作,但是第一行代码可能是一个心跳包,第二行可能是一个不定期发送的包。并且这些发送操作缓冲区不能同时聚集在一起。有没有办法在单线程(或多线程)中同步这些异步操作?

【问题讨论】:

  • 这只是偶然的,tcp 写入更有可能同步完成,因为操作系统为套接字使用了更大的缓冲区。考虑通过简单地合并两个缓冲区来取得进展,这样一次写入就可以完成工作。
  • 请研究如何使用 ASIO 进行异步 I/O。您需要触发一个异步操作,提供一个完成回调,您可以在其中触发下一个。

标签: c++ boost tcp boost-asio asio


【解决方案1】:

评论者是对的。在这种情况下,您可以轻松地使用缓冲序列 ("scatter/gather IO"):

std::vector<boost::asio::const_buffer> buffers { 
    boost::asio::buffer(*something), 
    boost::asio::buffer(*something2) 
};

boost::asio::async_write(*serialPort, buffers, handler);

Compiling On Coliru

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>

void handler(boost::system::error_code ec, size_t) {
    std::cout << __PRETTY_FUNCTION__ << ": " << ec.message() << "\n";
}

int main() {
    boost::asio::io_service svc;

    auto serialPort = std::make_shared<boost::asio::serial_port>(svc);

    auto something = std::make_shared<std::string>("hello world\n");
    auto something2 = std::make_shared<std::string>("bye world\n");

    std::vector<boost::asio::const_buffer> buffers { 
        boost::asio::buffer(*something), 
        boost::asio::buffer(*something2) 
    };

    boost::asio::async_write(*serialPort, buffers, handler);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2020-05-29
    相关资源
    最近更新 更多