Created
February 14, 2016 07:56
-
-
Save vmrob/ff20420a20c59b5a98a1 to your computer and use it in GitHub Desktop.
simple nonblocking read from std::cin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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)); | |
} | |
} |
@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
@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?