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
multiprocessingmodule 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 Standardimport 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 anasync deffunction (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
awaitwhen calling a coroutine (it returns a coroutine object, doesn't execute the function).