Back to Blog

Async/Await - Concurrent I/O Without Blocking (Python Tutorial #31)

Sandy LaneSandy Lane

Video: Async/Await - Concurrent I/O Without Blocking (Python Tutorial #31) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Async/Await - Concurrent I/O Without Blocking in Python

Asyncio in Python enables efficient concurrent I/O operations by using async/await syntax, allowing multiple tasks to run without blocking each other. This tutorial demonstrates how to write asynchronous coroutines, schedule them concurrently, and handle timeouts and exceptions gracefully.

Code

import asyncio

# Simulate an I/O-bound operation with asyncio.sleep
async def fetch_data(delay, name):
  print(f"Starting {name}")
  await asyncio.sleep(delay)  # Non-blocking wait
  print(f"Finished {name}")
  return f"Result from {name}"

async def main():
  # Run tasks sequentially
  print("Sequential execution:")
  result1 = await fetch_data(2, "Task 1")
  result2 = await fetch_data(2, "Task 2")
  print(result1, result2)

  # Run tasks concurrently using create_task and gather
  print("\nConcurrent execution:")
  task1 = asyncio.create_task(fetch_data(2, "Task 1"))
  task2 = asyncio.create_task(fetch_data(2, "Task 2"))
  results = await asyncio.gather(task1, task2)
  print(results)

  # Using wait_for to add a timeout
  try:
    await asyncio.wait_for(fetch_data(5, "Long Task"), timeout=3)
  except asyncio.TimeoutError:
    print("Timeout: Task took too long!")

# Entry point for asyncio programs
asyncio.run(main())

Key Points

  • Use async def to define coroutines and await to pause execution until an async operation completes.
  • asyncio.run() is the recommended way to start an async program in Python 3.7+.
  • asyncio.create_task() schedules coroutines to run concurrently in the background.
  • asyncio.gather() runs multiple coroutines concurrently and waits for all to finish, returning their results.
  • asyncio.wait_for() adds timeout protection to coroutines, raising TimeoutError if exceeded.