The event loop is the core of Asyncio, managing the execution of asynchronous tasks. You start the event loop using asyncio.run()
or loop.run_until_complete()
, and you can stop it using loop.stop()
. It’s important to ensure that the event loop is properly closed after use to release resources.
import asyncio
async def main():
print("Starting event loop")
await asyncio.sleep(1)
print("Stopping event loop")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
Tasks are created from coroutines and scheduled to run in the event loop. You can create tasks using asyncio.create_task()
or loop.create_task()
, and the event loop manages their execution.
import asyncio
async def my_task(name):
print(f"Task {name} started")
await asyncio.sleep(2)
print(f"Task {name} completed")
async def main():
task1 = asyncio.create_task(my_task("A"))
task2 = asyncio.create_task(my_task("B"))
await task1
await task2
asyncio.run(main())
In most cases, a single event loop is sufficient for an application. However, advanced scenarios may require multiple event loops, which can be managed using asyncio.set_event_loop()
and asyncio.new_event_loop()
. It’s crucial to avoid running multiple event loops in the same thread to prevent conflicts and unexpected behavior.
import asyncio
async def task1():
await asyncio.sleep(1)
print("Task 1 completed")
async def task2():
await asyncio.sleep(1)
print("Task 2 completed")
loop1 = asyncio.new_event_loop()
loop2 = asyncio.new_event_loop()
asyncio.set_event_loop(loop1)
loop1.run_until_complete(task1())
asyncio.set_event_loop(loop2)
loop2.run_until_complete(task2())
loop1.close()
loop2.close()