I am having trouble explaining the concept of a blocking vs a non-blocking function to my mom. What would be the best way to explain this? Is there a good analogy to use?
I don't know if you need to know this, but we are using Modkit for Vex IQ, a programming language very similar to Scratch.mit.edu.
Thank you so much!
You’re painting a room. You run out of paint, so you send your kid to the store to buy more paint, and you wait for them to come back. You block on the paint becoming available. The fetch_more_paint()
function is a “job”, and blocking since you can’t do anything else while the function is running. Once started, it takes over until it finishes.
You’re painting a room, planning to paint another room soon. You run out of paint. You tell the kid to go to the store to get more paint. Then you start to prep the next room for painting while you don’t have paint. When the kid returns with paint, you resume painting the first room. You don’t block on availability of paint: the fetch_more_paint()
is a request rather than a job: it is non-blocking. After issuing the request, you can continue doing whatever you need to do.
There are two ways of dealing with the kid coming back in the non-blocking scenario.
If you want to waste the least time switching tasks, you will finish prep work, and only then check if more paint is available to resume painting. Otherwise, you choose something else to do. This is polling between jobs - you check for the non-blocking function’s completed status when it’s convnient for you.
If you want the painting to be done as soon as possible, you let the kid tell you as soon as possible when the paint is available, and you resume painting right then. This has a bit more overhead, since you have to drop what you were doing at a possibly inopportune moment, doing a bit more work to change the task you’re on.