title: How to read stdin without blocking using C++ future?
body: <p>A test program <strong>StdoutWriter</strong> writes some text (<strong><em>{"id":0,"cmd":1}</em></strong>) to stdout in 1 second and then again after 5 seconds and then waits 10 seconds and exits.  I've ran this program by itself and verified the timing and output is correct.</p>
  
  <p>Another test program <strong>StdinReader</strong> (code given below), using a future reads stdin and prints each line.  <strong>StdinReader</strong> is not working as expected.</p>
  
  <p>I launch the two programs from terminal with:</p>
  
  <pre><code>./StdoutWriter | ./StdinReader
  </code></pre>
  
  <p>The problem I'm seeing is that the reading of each line seems to be blocking until StdoutWriter exits.  </p>
  
  <p>The <strong>wrong</strong> output being observed looks like:</p>
  
  <pre><code>waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  you wrote {"id":0,"cmd":1}
  waiting...
  you wrote {"id":0,"cmd":1}
  waiting...
  you wrote 
  waiting...
  you wrote 
  waiting...
  you wrote 
  </code></pre>
  
  <p><strong>Correct</strong> output should look like:</p>
  
  <pre><code>waiting...
  waiting...
  you wrote {"id":0,"cmd":1}
  waiting...
  waiting...
  waiting...
  waiting...
  waiting...
  you wrote {"id":0,"cmd":1}
  waiting...
  waiting...
  waiting...
  waiting...
  you wrote 
  waiting...
  you wrote 
  waiting...
  you wrote
  </code></pre>
  
  <p>Here's the code for StdinReader which I got from: <a href="https://gist.github.com/vmrob/ff20420a20c59b5a98a1" rel="nofollow noreferrer">https://gist.github.com/vmrob/ff20420a20c59b5a98a1</a></p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;chrono&gt;
  #include &lt;future&gt;
  #include &lt;string&gt;
  
  std::string GetLineFromCin() {
      std::string line;
      std::getline(std::cin, line);
      return line;
  }
  
  int main() {
  
      auto future = std::async(std::launch::async, GetLineFromCin);
  
      while (true) {
          if (future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
              auto line = future.get();
  
              // Set a new line. Subtle race condition between the previous line
              // and this. Some lines could be missed. To aleviate, you need an
              // io-only thread. I'll give an example of that as well.
              future = std::async(std::launch::async, GetLineFromCin);
  
              std::cout &lt;&lt; "you wrote " &lt;&lt; line &lt;&lt; std::endl;
          }
  
          std::cout &lt;&lt; "waiting..." &lt;&lt; std::endl;
          std::this_thread::sleep_for(std::chrono::seconds(1));
      }
  }
  </code></pre>