Recipe request: asyncio "spin off coroutine"

Chris Angelico rosuav at gmail.com
Wed Dec 14 13:44:57 EST 2016


When you work with threads, it's pretty straight-forward to spin off
another thread: you start it. Your current thread continues, and the
other one runs in parallel.

What's the most straight-forward way to do this in asyncio? I know
this has been asked before, but threads keep devolving, and I can't
find back the one I want :| This seems like a recipe that needs to be
in the docs somewhere. Consider:

async def parallel():
    print("Doing stuff in parallel")
    await asyncio.sleep(1)
    print("Done stuff in parallel")

async def do_stuff():
    print("Doing stuff")
    asyncio.spin_off(parallel()) # ???
    print("Doing more stuff")
    await asyncio.sleep(2)
    print("Done doing stuff")

Whenever do_stuff gets called, I want it to run to completion in two
seconds, AND the parallel process should run to completion during that
time.

What code should go on the "???" line to accomplish this?

ChrisA



More information about the Python-list mailing list