Home > Backend Development > C++ > How to Implement Non-Blocking Console Input in C Using Concurrency?

How to Implement Non-Blocking Console Input in C Using Concurrency?

Barbara Streisand
Release: 2024-10-29 17:04:02
Original
547 people have browsed it

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>
Copy after login

In this code:

  • getAnswer() is the function that reads user input in a separate thread.
  • The std::async function launches getAnswer() in its own thread.
  • The future.wait_for() function checks if getAnswer() has finished in a specified time frame (in this case, 5 seconds).
  • If getAnswer() has finished, its result is stored in the answer variable.
  • The program continues running and outputting information while the user input thread operates in the background.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template