Basic Pattern: Blocking Events

Learn about the basic pattern of handling blocking events.

Blocking nature of read/write operations

The most used source of events is I/O readiness. Most read and write operations are, by default, blocking in nature which slows down the program execution speed. If the program has to wait several seconds for a read to be completed, it cannot do anything else during that time. read is a synchronous call and when performed on a file, socket, etc., that has no data ready to be read, it blocks the program.

Solution: Don’t just wait!

The solution to that problem is to expect an event when the socket, for example, is ready to be read. While this is not the case, the program can deal with any other event that might happen.

The following example shows a simple program that sends an HTTP request to http://httpbin.org/delay/5. The URL returns a JSON content after five seconds of delay.

Get hands-on with 1200+ tech skills courses.