Home >Backend Development >C++ >How to Implement Non-Blocking Console Input in C Using Concurrency?
Non-Blocking Console Input in C
A common requirement in programming is handling user commands while a program continually runs and outputs information. Traditional console input methods in C block the program's execution until the user presses enter, but for non-blocking input, you need an alternative approach.
Solution: Concurrency
C 11 introduces the std::async and std::future library for concurrency. This allows you to spawn a separate thread for non-blocking input without halting the main program.
Implementation
The provided code demonstrates non-blocking console input:
<code class="cpp">#include <iostream> #include <future> #include <thread> #include <chrono> std::string getAnswer() { std::string answer; std::cin >> answer; return answer; } int main() { std::chrono::seconds timeout(5); std::cout << "Do you even lift?" << std::endl << std::flush; std::string answer = "maybe"; //default to maybe std::future<std::string> future = std::async(getAnswer); if (future.wait_for(timeout) == std::future_status::ready) answer = future.get(); std::cout << "the answer was: " << answer << std::endl; exit(0); }</code>
In this code:
The above is the detailed content of How to Implement Non-Blocking Console Input in C Using Concurrency?. For more information, please follow other related articles on the PHP Chinese website!