Skip to content

Instantly share code, notes, and snippets.

@vmrob
Created February 14, 2016 07:56
Show Gist options
  • Save vmrob/ff20420a20c59b5a98a1 to your computer and use it in GitHub Desktop.
Save vmrob/ff20420a20c59b5a98a1 to your computer and use it in GitHub Desktop.
simple nonblocking read from std::cin
#include <iostream>
#include <chrono>
#include <future>
#include <string>
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 << "you wrote " << line << std::endl;
}
std::cout << "waiting..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
@andyflinn
Copy link

@vmrob I like this approach. A small notice only: instead of calling sleep at the end of the while loop, why don't you put std::chrono::seconds(1) in the wait_for instead?

i think he wants mutex (critical condition) to be over as fast as possible, so he doesn't block the io thread

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment