Sobes.tech
Junior — Middle

Can you explain the concept of non-blocking input/output and how it differs from blocking?

sobes.tech AI

Answer from AI

Non-blocking I/O allows a program to initiate an input/output operation and continue executing without waiting for its completion. This increases efficiency, especially when working with multiple connections or files, as the program does not idle while waiting.

Unlike blocking I/O, where execution halts until data is received or the operation is complete, non-blocking I/O returns control immediately, allowing other tasks to be processed.

Example in Python using a non-blocking socket:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)  # Set non-blocking mode
try:
    sock.connect(('example.com', 80))
except BlockingIOError:
    pass  # Operation in progress

# Other actions can be performed while the connection is being established

Thus, non-blocking I/O improves the responsiveness and scalability of applications.