Possible to stop cin from waiting input?

后端 未结 1 1465
盖世英雄少女心
盖世英雄少女心 2021-01-05 00:46

In a graphical application I execute debug commands using the console input. When the console is created a new thread is also created to gather the user commands that handle

相关标签:
1条回答
  • 2021-01-05 01:39

    I am not much of a Windows programmer, I know a whole lot more about Unix. And I am totally unfamiliar with boost::thread. That said, based on the advice at the bottom of this MSDN page, here is my recommendation:

    • Create an event object before you create the console-reading thread.
    • When you want to shut down, call SetEvent on the event object immediately before calling the thread's ->join method.
    • Change the main loop in your console-reading thread to block in WaitForMultipleObjects rather than istream::operator>>, something like this:

      for (;;) {
          HANDLE h[2];
          h[0] = GetStdHandle(STD_INPUT_HANDLE);
          h[1] = that_event_object_I_mentioned;
          DWORD which = WaitForMultipleObjects(2, h, FALSE, INFINITE);
      
          if (which == WAIT_OBJECT_0)
              processConsoleCommand();
          else if (which == WAIT_OBJECT_0 + 1)
              break;
          else
              abort();
      }
      
    • This thread must take care not to do any blocking operation other than the WaitForMultipleObjects call. Per the discussion in the comments below, that means processConsoleCommand can't use cin at all. You will need to use the low-level console input functions instead, notably GetNumberOfConsoleInputEvents and ReadConsoleInput, to ensure that you do not block; you will need to accumulate characters across many calls to processConsoleCommand until you read a carriage return; and you will also need to do your own echoing.

    0 讨论(0)
提交回复
热议问题