Possible to stop cin from waiting input?

五迷三道 提交于 2019-11-30 19:03:34

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!