ASIO与Win32:为什么Windows :: Object_handle :: async_wait之后读取文件阻止?
我正在尝试从Windows上使用ASIO从STDIN中读取异步。
为此,我尝试使用 ASIO :: Windows :: Object_handle 。
我希望在async_wait
在stdin句柄上,:: readfile
在同一句柄上不应阻止。
但是,似乎并非如此。在以下程序中,我希望我的第一个Coroutine的输入回声与测试N
打印输出相交。
相反,:: ReadFile
呼叫正在阻止io_context.run()
,因此test n
仅在我按在返回返回的情况下才会发生安慰。
#include <sdkddkver.h>
#include <chrono>
#include <iostream>
#include "asio/asio.hpp"
int main() {
using namespace std::chrono_literals;
asio::io_context ctx;
asio::high_resolution_timer timer(ctx);
asio::windows::object_handle stdin_handle(ctx,
::GetStdHandle(STD_INPUT_HANDLE));
/// stdin loop
asio::co_spawn(
ctx,
[&]() -> asio::awaitable<void> {
for (;;) {
co_await stdin_handle.async_wait(asio::use_awaitable);
char buf[100];
DWORD n;
//
I'm trying to read asynchronously from stdin using ASIO on windows.
To this end, I tried to use an asio::windows::object_handle
.
I would expect that after async_wait
ing on the STDIN handle, ::ReadFile
on the same handle should not block.
However, it seems that this is not the case. In the following program, I would expect echos of my input from the first coroutine, interlaced with the test n
printouts from the second.
Instead, the ::ReadFile
call is blocking the io_context.run()
, so the test n
prints only happen after I presss return in the console.
#include <sdkddkver.h>
#include <chrono>
#include <iostream>
#include "asio/asio.hpp"
int main() {
using namespace std::chrono_literals;
asio::io_context ctx;
asio::high_resolution_timer timer(ctx);
asio::windows::object_handle stdin_handle(ctx,
::GetStdHandle(STD_INPUT_HANDLE));
/// stdin loop
asio::co_spawn(
ctx,
[&]() -> asio::awaitable<void> {
for (;;) {
co_await stdin_handle.async_wait(asio::use_awaitable);
char buf[100];
DWORD n;
// ???? this is blocking?
ReadFile(stdin_handle.native_handle(), buf, sizeof(buf), &n, NULL);
std::cout << "input (" << n << "): " << std::string_view(buf, n);
}
},
asio::detached);
/// stdout loop
asio::co_spawn(
ctx,
[&]() -> asio::awaitable<void> {
for (int i = 0; i < 10; i++) {
std::cout << "test " << i << "\n";
timer.expires_after(1s);
co_await timer.async_wait(asio::use_awaitable);
}
},
asio::detached);
ctx.run();
return 0;
}
What am I doing wrong? Does object_handle::async_wait
wait for things other than actual input? How do I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论