ASIO与Win32:为什么Windows :: Object_handle :: async_wait之后读取文件阻止?

发布于 2025-02-03 18:17:00 字数 1139 浏览 4 评论 0原文

我正在尝试从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_waiting 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文