Asyncio is a powerful framework in Python that enables writing asynchronous, non-blocking code. A key advantage of asyncio is that it uses a single-thread under the hood, yet can handle many tasks concurrently.
The Event Loop
The core of asyncio is the event loop. This loop runs in a single thread and handles all the asynchronous tasks and IO operations. So when you call
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
asyncio.run(main())
So how does it process multiple things with one thread? The key is that asyncio uses cooperative multitasking. When an async function needs to wait for some IO or timer, it will yield control back to the event loop, allowing other tasks to run.
This makes asyncio very lightweight compared to using multi-threading or multi-processing.
Creating Additional Threads
The asyncio event loop runs in the main thread by default. You can also create additional threads manually and run tasks there.
thread = threading.Thread(target=other_func)
thread.start()
But typically you want to offload CPU-bound work to a thread and keep async tasks inside the main event loop thread.
Key Takeaways
Using asyncio single-threaded design with async/await syntax makes it easy to write high-performance concurrent programs in Python.