C의 비차단 콘솔 입력
프로그래밍의 일반적인 요구 사항은 프로그램이 지속적으로 실행되고 정보를 출력하는 동안 사용자 명령을 처리하는 것입니다. C의 기존 콘솔 입력 방법은 사용자가 Enter를 누를 때까지 프로그램 실행을 차단하지만 비차단 입력의 경우 대체 접근 방식이 필요합니다.
해결책: 동시성
C 11에는 동시성을 위한 std::async 및 std::future 라이브러리가 도입되었습니다. 이를 통해 기본 프로그램을 중단하지 않고 비차단 입력을 위한 별도의 스레드를 생성할 수 있습니다.
구현
제공된 코드는 비차단 콘솔 입력을 보여줍니다.
<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>
이 코드에서:
위 내용은 동시성을 사용하여 C에서 비차단 콘솔 입력을 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!