Question: I have handle that I got via `stdinHandle = GetStdHandle(STD_INPUT_HANDLE)` and I have separate thread which execute such code:

```
while (!timeToExit) {
  char ch;
  DWORD readBytes = 0;
  if (!::ReadFile(stdinHandle, &ch, sizeof(ch), &readBytes, nullptr)) {
    //report error
    return;
  }
  if (readBytes == 0)
      break;
  //handle new byte
}

```

where `timeToExit` is `std::atomic<bool>`.

I wan to stop this thread from another thread. I tried this:

```
timeToExit = true;
CloseHandle(stdinHandle);

```

and code hangs in `CloseHandle`.

The code hangs while program is running by other program that uses
`CreatePipe` and `DuplicateHandle` to redirect input of my program to pipe.

So how should I stop `while (!timeToExit)..` thread in win32 way?
Or may be I should some how change `while (!timeToExit)..` thread to make it possible
to stop it?

**Update**
I thought about usage of `WaitForMultipleObjects` before call of `ReadFile` with 
stdin and event as arguments, and trigger event in other thread,
but there is no mention of anonymous pipe as possible input for `WaitForMultipleObjects`, plus I tried when stdin connected to console,
and it become useless (always return control without delay) after the first character typed into console,
looks like I have to use `ReadConsoleInput` in this case, instead of `ReadFile`?

Answer: 
When reading from a console's actual STDIN, you can use [`PeekConsoleInput()`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684344.aspx) and [`ReadConsoleInfo()`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961.aspx) instead of `ReadFile()`.

When reading from an (un)named pipe, use [`PeekNamedPipe()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365779.aspx) before calling `ReadFile()`.

This will allow you to poll STDIN for new input before actually reading it, and then you can check your thread termination status in between polls.

You can use [`GetFileType()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364960.aspx) to detect what kind of device is attached to your `STD_INPUT_HANDLE` handle.
The safest way to do this would be to call [ReadFile](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v=vs.85).aspx) asynchronously (non-blocking) using the OVERLAPPED structure etc. This can be done from your main thread.

If/when you need to cancel it, call [CancelIo](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363791(v=vs.85).aspx) (from same thread that called ReadFile) or [CancelIoEx](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363792(v=vs.85).aspx) (if from another thread).

You might be able to make your current approach work; if you mark timeToExit as volatile, it may not hang, but that approach commonly creates bigger problems.