The asyncio module in Python provides infrastructure for writing asynchronous code using the async/await syntax. At the heart of asyncio is the event loop which runs the asynchronous tasks.
To leverage concurrency and parallelism in Python, you need to understand how to properly add tasks to asyncio event loops. Here are some key points:
Queue Up Tasks with loop.create_task()
The event loop provides a
import asyncio
async def my_coro():
print('Hello world')
loop = asyncio.get_event_loop()
task = loop.create_task(my_coro())
loop.run_until_complete(task)
This queues up
Submit Tasks with ensure_future()
You can also submit tasks using
import asyncio
async def my_coro():
print('Hello again!')
loop = asyncio.get_event_loop()
asyncio.ensure_future(my_coro())
loop.run_forever()
Watch Out for Blocking Calls
Care must be taken to avoid blocking calls which pause execution waiting on long-running I/O. These will stall the event loop. Use the provided
In summary, asyncio event loops manage task execution. Enqueue jobs with