This is a good example which is easy to understand, thanks. However, this appears to be a 'blocking' callback. I'm really hoping for an example of a 'non-blocking' one. Or is it I'm just misinterpreting the terminology here?
| [reply] |
The problem is that your callback is blocking too. It sleeps for one second, during which time nothing else can happen.
An event loop will typically have listeners registered with it. When a listener hears a message that is of interest to it, the callback will be invoked. If the callback is doing work that might consume a lot of time, that callback itself may need to break its work into smaller chunks that can be registered with the event loop too, or may need to fork a process. Or both perhaps.
Take the example of asynchronous web apps. You may have an app that listens for http requests. So that listener sits in the event loop waiting for something to happen. When a request comes in, the listener decides if the request is interesting to it (for example, did we get a get request with a useful path?). If so, it fires off the callback associated with the specific get request (this may be handled by a route, in mojolicious).
Now maybe that get request handler needs to scrape info from example.com. The get request handler could hit the remote server and wait, during which time the application blocks. Or it could fire off a request, and then install a listener in the event loop to listen for the response from the remote server. At that point the get request handler is free to return control back to the main event loop.
Now the main event loop continues listening for get requests, but is also listening for a response from the remote server. And when that response comes, another callback can be fired off, possibly to render the scraped content.
So asynchronous apps that use an event loop usually have to be designed at every level to not block; to listen, react, and register callbacks that respond to events. Callbacks may still set up listeners, and may themselves install callbacks to happen.
| [reply] |