Sobes.tech
Junior — Middle

Is it possible to run multiple event loops in one Python thread and how to implement it?

sobes.tech AI

Answer from AI

In Python, the standard asyncio library does not support running multiple event loops in the same thread simultaneously. Each thread can only have one active event loop.

If you need to work with multiple event loops, you typically create separate threads or processes for each loop. Only one event loop can be run in a single thread.

Example of running an event loop in a separate thread:

import asyncio
import threading

def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

new_loop = asyncio.new_event_loop()
threading.Thread(target=start_loop, args=(new_loop,)).start()

# Now you can run coroutines from another thread in new_loop