RecentlyOdds & Ends
now playing

Python asyncio

asyncio is a Python library enabling concurrent operations using the async/await syntax. Under the hood, it’s all coroutines.

== (?) cooperative multitasking; cooperative concurrency ==

asyncio works by establishing a singular global event loop. Coroutines (or “tasks”) are defined with async def, and the event loop constantly monitors the existing tasks, running them as needed. asyncio is fundamentally single-threaded.

asyncio vs regular threading

-asynciothreading
Memory~KB per coroutine~1-8MB per thread
Scaling100k+ concurrent tasksHundreds at most
Context switchCheap (userspace)Expensive (kernel)
Race conditionsOnly at await pointsAnywhere - need locks
EcosystemEverything must be async-awareAny code works
BlockingBreaks everythingFine
ComplexityHarder to understandSimpler mental model
Best forHigh-volume IOLegacy/blocking code

Using asyncio in combination with threads

I would recommend creating a single event loop in a background thread and have it service all your async needs. It doesn’t matter that your coroutines never end; asyncio is perfectly capable of executing multiple such functions in parallel. (source - stackoverflow)