Interview question
How does asyncio work, and how is it different from threading? asyncio कैसे काम करता है, और threading से कैसे अलग है?
Answer
asyncio provides concurrency within a SINGLE thread using cooperative multitasking - coroutines voluntarily yield control at await points, rather than being preemptively switched like OS threads.
| Aspect | threading | asyncio |
|---|---|---|
| Concurrency model | Preemptive (OS switches threads) | Cooperative (code yields via await) |
| Number of threads | Multiple OS threads | Single thread |
| Switching overhead | Higher (OS-level context switch) | Lower (just function call/return) |
| Best for | I/O-bound, blocking libraries | I/O-bound, async-aware libraries |
import asyncio
async def fetch_data(name, delay):
print(f'{name}: starting')
await asyncio.sleep(delay) # yields control here, doesn't block the thread
print(f'{name}: done')
return f'{name} result'
async def main():
# Running concurrently - all three start almost immediately
results = await asyncio.gather(
fetch_data('Task A', 2),
fetch_data('Task B', 1),
fetch_data('Task C', 3)
)
print(results)
asyncio.run(main())
# Task A: starting, Task B: starting, Task C: starting (all immediately)
# Task B: done (after 1s), Task A: done (after 2s), Task C: done (after 3s)
# Total time ~3s, NOT 6s (2+1+3) - they ran concurrently, not sequentially
# CRITICAL: asyncio only helps if the I/O operation is 'awaitable'
# (async-aware). Blocking calls like time.sleep() or requests.get()
# inside an async function STILL block the entire event loop
async def bad_example():
import time
time.sleep(2) # BLOCKS the whole event loop, defeats the purpose of asyncioasyncio एक ही thread के अंदर cooperative multitasking से concurrency देता है - coroutines await points पर स्वेच्छा से control छोड़ते हैं, OS threads की तरह preemptively switch नहीं होते।
| पहलू | threading | asyncio |
|---|---|---|
| Concurrency model | Preemptive | Cooperative (await से) |
| Threads की संख्या | Multiple | एक |
| Switching overhead | ज़्यादा | कम |
import asyncio
async def fetch_data(name, delay):
print(f'{name}: starting')
await asyncio.sleep(delay) # यहां control yield होता है
print(f'{name}: done')
return f'{name} result'
async def main():
results = await asyncio.gather(
fetch_data('Task A', 2),
fetch_data('Task B', 1),
fetch_data('Task C', 3)
)
print(results)
asyncio.run(main())
# कुल समय ~3s, 6s नहीं - concurrently चले
# ज़रूरी: asyncio सिर्फ 'awaitable' I/O के साथ काम करता है
# time.sleep() जैसे blocking calls पूरे event loop को block कर देते हैं
async def bad_example():
import time
time.sleep(2) # पूरा event loop block हो जाता हैWas this answer clear?