Blocking or Non-Blocking
that’s a question
Have you heard of Non-Blocking APIs, what it is and why we should consider using it? If you haven’t known yet, this is the post for you.
Blocking vs Non-Blocking
Back in previous century (20th century), every C developer should know this function.
int getchar();
This function reads a character from std in (it’s the keyboard back then). So if you want to write a simple game using the keyboard as the controller, this maybe a useful function to use.
The problem of this function is it’s a blocking function. It blocks the current thread and wait for the key to be pressed. If your code looks like this, nobody is impressed.
while (gameIsRunning)
{
moveEnemyShipsAround(); int key = getchar();
handleKeyEvent(key)
}
Everytime the getchar()
function is called, the execution of the code is paused, hence the enemy ships stop moving around.
The solution to this is using two other functions. kbhit()
and getch()
, kbhit()
check if the is a pending character in the input buffer and getch()
silently read it from the buffer.
while (gameIsRunning)
{
moveEnemyShipsAround();
if (kbhit())
{
int key = getch();
handleKeyEvent(key);
}
}
In this case, the game will keep running, the ships continue moving around, only there is a key pressed, the…