Junior — Middle
What solution is used for handling tasks limited by input/output operations?
sobes.tech AI
Answer from AI
For handling I/O-bound tasks, Python often uses asynchronous programming with asyncio or multithreading.
Since I/O operations typically block the thread, the asynchronous approach allows running other tasks while waiting for I/O to complete, increasing efficiency.
Example using asyncio to read multiple files simultaneously:
import asyncio
async def read_file(filename):
print(f"Start reading {filename}")
await asyncio.sleep(1) # simulate I/O operation
print(f"Finished reading {filename}")
async def main():
await asyncio.gather(
read_file('file1.txt'),
read_file('file2.txt'),
read_file('file3.txt')
)
asyncio.run(main())
This approach efficiently utilizes waiting time for I/O without blocking the main thread. For CPU-bound tasks, it's better to use multiprocessing.