1

Could somebody explain me why I can't execute my tasks if I start the loop without any added tasks before? (Python 3.7)

import asyncio
import threading    

def run_forever(loop):
    loop.run_forever()

async def f(x):
    print("%s executed" % x)

# init is called first
def init():
    print("init started")

    loop = asyncio.new_event_loop()

    # loop.create_task(f("a1")) # <--- first commented task

    thread = threading.Thread(target=run_forever, args=(loop,))
    thread.start()

    loop.create_task(f("a2")) # <--- this is not being executed

    print("init finished")

If I leave comment on # loop.create_task(f("a1")) the execution is:

init started
init finished

Uncommented execution is:

init started
init finished
a1 executed
a2 executed

Why so? I wanted to create a loop and to add tasks in the future.

1 Answer 1

2

Unless explicitly stated otherwise, asyncio API is not thread-safe. This means that calling loop.create_task() from a thread other than the one that runs the event loop will not properly synchronize with the loop.

To submit the task to the event loop from a foreign thread, you need to invoke asyncio.run_coroutine_threadsafe instead:

asyncio.run_coroutine_threadsafe(f("a2"), loop)

This will wake up the loop to alert it that a new task has arrived, and it also returns a concurrent.futures.Future which you can use to obtain the result of the coroutine.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.