gpt4 book ai didi

c++ - boost::asio::async_read 在不满足完成条件的情况下结束

转载 作者:行者123 更新时间:2023-11-30 05:28:57 31 4
gpt4 key购买 nike

在 Windows 上,我观察到如果 async_read 操作在串行端口上成功完成,我会立即启动另一个 async_read 操作来读取 n 字节,第二个 async_read 操作立即意外完成并成功传输 0 字节。

  • 在第二次async_read操作之后,如果发起第三次async_read操作来读取n字节,那么它将完成成功并传输了 n 个字节

    // where buffer_size(buffer) and n are both greater than 1
    async_read(serial, buffer, transfer_exactly(n), [](error, bytes_transferred) {
    // completes with error=success and bytes_transferred=n
    async_read(serial, buffer, transfer_exactly(n), [](error, bytes_transferred) {
    // complete with error=success and bytes_transferred=0
    async_read(serial, buffer, transfer_exactly(n), [](error, bytes_transferred) {
    // completes with error=success and bytes_transferred=n
    });
    });
    });
  • 如果在第一个和第二个async_read 操作之间执行 1 毫秒休眠,则第二个操作将成功完成并传输 n 个字节

    // where buffer_size(buffer) and n are both greater than 1
    async_read(serial, buffer, transfer_exactly(n), [](error, bytes_transferred) {
    // completes with error=success and bytes_transferred=n
    sleep_for(milliseconds(1));
    async_read(serial, buffer, transfer_exactly(n), [](error, bytes_transferred) {
    // completes with error=success and bytes_transferred=n
    });
    });

为什么会发生这种情况,我该如何避免?


具体而言,我在 Windows 上使用 Boost.Asio 通过 ATXMEGA-192A3U 模拟的 RS232 与微 Controller 通信。我向 Controller 发送启动命令并读取超时的输出。我通过调用下面给出代码的 ReadPort 函数读取输出。该程序连续执行以下阅读任务:

  1. 检查微 Controller 对启动命令的应答。此读取成功读取了我期望的 3 个字符:R\r\n
  2. 从 Controller 读取 n 个字节的输出,持续数百毫秒。

步骤 2 中的 async_read 操作意外成功完成,尽管没有读取请求的字节数。

class BoostBasedCommunication
{
public:
BoostBasedCommunication();
~BoostBasedCommunication(void);
/*...*/
virtual int ReadPort(
int const numberOfCharacters, // maximum number of characters to be read
unsigned long const globalTimeout, // maximum time the operation is allowed to take in ms
unsigned long const intermediateTimeout, // maximum time allowed between two consequtive characters in ms
int& numberOfCharactersRead
);
/*...*/

private:
/*...*/
std::vector<unsigned char> inputBuffer; ///< buffer to save data to that is received
size_t numberOfBytesRead; ///< Number of bytes read
int lastErrorCode; ///< last error code
io_service my_io_service; ///< boost io service class
serial_port port; ///< boost serial port class
/*...*/
};

// Reads from the port until numberOfCharacters have been read, or the
// deadline_timer has expired, or the time between two consecutive calls of
// the completion condition is larger than intermediateTimeoutMS

int BoostBasedCommunication::ReadPort(
int const numberOfCharacters, // maximum number of characters to be read
unsigned long const globalTimeoutMS, // maximum time the operation is allowed to take in ms
unsigned long const intermediateTimeoutMS, // maximum time allowed between two consecutive characters in ms
int& numberOfCharactersRead // Actual number of characters read
)
{
try
{
OutputDebugStringA("ReadPort called\r\n");
my_io_service.reset();
deadline_timer gloabalTimeout(my_io_service);
inputBuffer.resize(numberOfCharacters);
timeoutHandler myGlobalTimeoutHandler(&port);

completion_handler_2 myHandler(&gloabalTimeout, numberOfBytesRead);
completion_condition_2 my_completion_condition(intermediateTimeoutMS, numberOfCharacters);

// Set the timer
gloabalTimeout.expires_from_now(boost::posix_time::milliseconds(globalTimeoutMS));
gloabalTimeout.async_wait(myGlobalTimeoutHandler);

async_read(port, boost::asio::buffer(inputBuffer, numberOfCharacters), my_completion_condition, myHandler);

my_io_service.run(); // run the io service
numberOfCharactersRead = numberOfBytesRead;
}
catch (std::exception&)
{
return COMMUNICATIONFAILED;
}
return NOERROR;
}

class completion_condition_2
{
public:
completion_condition_2(
long intermediateTimeOutTime,
size_t numberOfCharactersTobeRead
) :intermediateTimeOutTime(intermediateTimeOutTime),
numberOfCharactersTobeRead(numberOfCharactersTobeRead)
{}

std::size_t operator()(
const boost::system::error_code& error, // Result of latest async_read_some operation.
std::size_t bytes_transferred // Number of bytes transferred so far.
)
{
if (error)
{
OutputDebugStringA(("completion_condition received error code: " + error.message() + "\r\n").c_str());

if (error.value() == ERROR_OPERATION_ABORTED)
{
return 0;
}
}

/* ...Code concerning the intermediate timeout, which is commented out...*/

if (numberOfCharactersTobeRead <= bytes_transferred) // Enough data has been read
{
std::stringstream message;
message << "completion_condition: bytes transferred: " << bytes_transferred << " of " << numberOfCharactersTobeRead << " => done!" << std::endl;
OutputDebugStringA(message.str().c_str());
return 0;
}
else // More data should be read.
{
std::stringstream message;
message << "completion_condition: bytes transferred: " << bytes_transferred << " of " << numberOfCharactersTobeRead << " => continue!" << std::endl;
OutputDebugStringA(message.str().c_str());
return numberOfCharactersTobeRead - bytes_transferred;
}
}

private:
size_t numberOfCharactersTobeRead; ///< Number of characters to be read
};

class completion_handler_2 {
public:
completion_handler_2(
deadline_timer* _globalTimeout,
size_t& numberOfBytesRead
) :_globalTimeout(_globalTimeout),
numberOfBytesRead(numberOfBytesRead)
{
}

void operator()(
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes read.
)
{
OutputDebugStringA(("completion handler called with error code: " + error.message() + "\r\n").c_str());
if (error)
{
if (error.value() == ERROR_OPERATION_ABORTED)
{
numberOfBytesRead = bytes_transferred;
return;
}
else
{
BOOST_THROW_EXCEPTION(std::exception("Communication failed"));
}
}

OutputDebugStringA("completion handler: timeout cancelation.\r\n");

_globalTimeout->cancel();
numberOfBytesRead = bytes_transferred;
}

private:
deadline_timer* _globalTimeout; ///< global timeout deadline timer
size_t& numberOfBytesRead; ///< number of bytes read
};

当我执行第一个按预期工作的读取时,我收到以下输出:

ReadPort called
completion_condition: bytes transferred: 0 of 3 => continue!
completion_condition: bytes transferred: 3 of 3 => done!
completion handler called with error code: success
completion handler timeout cancelation.
timeoutHandler received error code: The I/O operation has been aborted because of either a thread exit or an application request

如果我在第一次读取完成后立即执行另一次读取,则操作会在 2 毫秒后完成,并显示以下输出:

ReadPort called
completion_condition: bytes transferred: 0 of 1024 => continue!
completion handler called with error code: success // Why is the completion handler called here, although the completion condition did not return 0?
completion handler timeout cancelation.
timeoutHandler received error code: The I/O operation has been aborted because of either a thread exit or an application request

第三次读取,紧接着最后一次读取按预期工作:

ReadPort called
completion_condition: bytes transferred: 0 of 1024 => continue!
completion_condition: bytes transferred: 8 of 1024 => continue!
...
completion_condition: bytes transferred: 88 of 1024 => continue!
completion_condition: bytes transferred: 96 of 1024 => continue!
timeoutHandler called cancel of seriel port.
completion_condition received error code: The I/O operation has been aborted because of either a thread exit or an application request
completion handler called with error code: The I/O operation has been aborted because of either a thread exit or an application request

最佳答案

简而言之,根本问题是:

  • Asio 对 ReadFile 的解读带有超时的 API 契约(Contract)不正确
  • 通信驱动程序违反了ReadFile API契约(Contract)

最简单的解决方案是在应用程序代码中考虑这种行为,并发出另一个 async_read如果前一个成功完成并读取 0 个字节,则执行操作。根据通信驱动程序的实现,读取之间 1 毫秒的休眠可能有效。


COMMTIMEOUTS 文档指出对于读取间隔超时:

The maximum time allowed to elapse before the arrival of the next byte on the communications line, in milliseconds. If the interval between the arrival of any two bytes exceeds this amount, the ReadFile operation is completed and any buffered data is returned. [...]

Asio 对文档(即强调文本)的解释是给定 ReadFile 操作,读取间隔超时开始于第一个字节被读取之后。言外之意就是如果ReadFile被请求读取超过 0 个字节,Asio 不期望 ReadFile操作返回一个状态,指示它已成功同步或异步读取 0 字节。通过这种解释,Asio 的 implementation将串行端口的读取间隔超时配置为 1 毫秒1

// Set up timeouts so that the serial port will behave similarly to a
// network socket. Reads wait for at least one byte, then return with
// whatever they have. Writes return once everything is out the door.
::COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 0;

async_read 是在对中间 async_read_some 的零次或多次调用中实现的组合操作操作。 async_read操作解释中间体 async_read_some操作成功完成并传输了 0 个字节,就好像组合操作不会有进一步的进展,因此 async_read操作完成。当底层系统调用 ReadFile 时,这种解释就会出现问题。意外同步完成并成功读取 0 字节。

有了这些细节,替代解决方案是:

  • 修补通信驱动程序,以便超时间隔仅在 ReadFile 时开始操作一旦读取了至少一个字节
  • 给 Asio 打补丁。如果有人详细说明了 ReadFile 的观察行为并发现它仅在 ReadFile 时发生操作同步完成,然后可以修补 async_read_some() win_iocp_handle_service::start_read_op 内运行.否则,可以修补各种 read_op特化,以便他们的 completion predicate如果已读取 0 个字节,但已请求超过 0 个字节,则不会退出。

<子>1。如果通信驱动程序的实现允许读取间隔超时,该超时从读取 ReadFile<sub>n</sub> 的最后一个字节开始操作影响ReadFile<sub>n+1</sub>在读取间隔超时间隙内启动的操作,然后在 ReadFile<sub>n</sub> 之间休眠和 ReadFile<sub>n+1</sub>在读取间隔超时期间,当提供的缓冲区大小大于 0 字节时,将阻止 Asio 读取操作成功完成和 0 字节。

关于c++ - boost::asio::async_read 在不满足完成条件的情况下结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597923/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com