[Python] Is it safe to create asyncio event loop in one thread and run it in another thread...

Discussão em 'Python' iniciado por Stack, Dezembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I want to know if it's safe to create an asyncio event loop in one thread and run the loop in another while having the ability to cancel it from outside the thread in which the event loop is running. I want to run an async function in a thread while also having ability to cancel it from outside the thread.

    Here is the code I am currently using. I want to know if this is the correct approach or if there is a simpler/better way to do this:

    import asyncio
    from concurrent.futures import ThreadPoolExecutor, CancelledError
    import time

    pool = ThreadPoolExecutor()
    loop = asyncio.new_event_loop()


    def start_event_loop(loop):
    asyncio.set_event_loop(loop) # is this necessary?
    loop.run_forever()


    pool.submit(start_event_loop, loop)


    async def long_task():
    try:
    while True:
    print("Running...")
    await asyncio.sleep(1)
    except asyncio.CancelledError:
    print("Task was cancelled")


    future = asyncio.run_coroutine_threadsafe(long_task(), loop)

    time.sleep(5)
    loop.call_soon_threadsafe(future.cancel)

    try:
    future.result()
    except CancelledError:
    time.sleep(1)
    print("Future was cancelled")

    loop.call_soon_threadsafe(loop.stop) # can i reuse the loop?

    while loop.is_running():
    print("Wating for loop to stop...")
    time.sleep(0.1)

    loop.close() # is this necessary?
    print("Loop stopped")


    This is based on this article and this question.

    Also, there are few more questions I'd like to ask:


    1. Is it necessary to use asyncio.set_event_loop? Both of them produce the same output.


    2. Is it okay to reuse the event loop after stopping it or should I create a new loop each time after stopping the loop?


    3. Is it necessary to close the loop after you are done with it?

    Continue reading...

Compartilhe esta Página