Core Module
12 min forge

Asyncio & the GIL

Concurrency in Python: Threads vs Processes vs Asyncio.

Asyncio & the GIL

πŸ“˜ What is it

Concurrency in Python is unique because of the Global Interpreter Lock (GIL). Understanding how to handle I/O-bound vs CPU-bound tasks is a common advanced interview topic.

πŸ—οΈ The GIL (Global Interpreter Lock)

The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes at once.

  • Impact: Multi-threading in Python doesn't provide a speed boost for CPU-bound tasks (it can actually slow them down).
  • Solution: Use for I/O-bound tasks (like network requests) or use the multiprocessing module for CPU-bound tasks.

⚑ Asyncio

asyncio is a library to write single-threaded concurrent code using async/await syntax.

  • Event Loop: The core of asyncio, it manages execution of asynchronous tasks.
  • Coroutines: Functions defined with async def.
  • Await: Pauses execution of the coroutine until the awaited task is complete, yielding control back to the event loop.

πŸ’» Code example

python Standard
import asyncio async def fetch_data(): print("Start fetching...") await asyncio.sleep(2) # Simulating I/O print("Data fetched!") return {"data": 123} async def main(): result = await fetch_data() print(result) asyncio.run(main())

❌ Common mistakes

  • Blocking inside async: Calling a blocking function (like time.sleep) inside an async def function (it blocks the entire event loop).
  • GIL misconception: Thinking that Python doesn't support concurrency at all because of the GIL.
  • Async calls: Forgetting to use await when calling a coroutine (it returns a coroutine object, doesn't execute the function).