Aussie AI
Busy waiting for input
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Busy waiting for input
Humans are very slow compared to computers. In particular, a computer can do much work in the background, even when handling the (slow) interactive input of a human. Hence, one method of improving efficiency is to perform background processing while awaiting input, instead of using blocking input that waits for a keypress before doing anything. In other words, you can't use std::cin or scanf for non-blocking keypress polling.
A common example of this idea is chess-playing programs that “think” during their opponent’s time. The computer can continue its game-tree analysis while waiting for the player to press a key or click a mouse. The C++ standard provides no simple standardized function for non-blocking input. In general, there are two ways:
- Keyboard polling API calls (non-portable).
- Multi-threading with input on one thread and processing on another.
There are various non-portable ways to poll for key presses.
For example, on Windows there's the “_getch
” or “kbhit
” functions (also “_kbhit
”), which are all deprecated.
Assuming you've found a workable polling API call,
at some regular interval, perhaps before each node of the game tree
is analyzed, the chess program checks if a key has been pressed.
If a key has been pressed, the chess program stores
information about its current analysis, and processes the user's keystroke. Unless the key press
completes the user’s move, the background analysis can continue after processing the key.
Overall, there's no simple and standardized way to do non-blocking input in C++. This is probably because of C’s ancestry, where it was difficult to poll the keyboard on a traditional UNIX line terminal. Multi-threading can be used in C++ to achieve the result instead.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |