Captain Midnight
Captain Midnight

Reputation: 33

what happens if you await a coroutine that doesn't itself have await? (asyncio)

I'm trying to understand how python's asyncio, and there is one particular situation that confuses me. What happens if you await a coroutine that is just a normal routine in all but name?

I.E.:

async def A():
    time.wait( 1 )

async def B():
    await A()

Will this just run like a normal synchronous program, and thus the async and awaits are superfluous? Or will A() be split off into a separate thread to run synchronously with other awaited functions?

Upvotes: 1

Views: 183

Answers (1)

jwal
jwal

Reputation: 660

As python_user says, it's only one thread, asyncio multiplexes functions inside a single event loop. For this to work slow (IO bound but not CPU intensive) functions must hand back execution control to the event loop, await does this. Note time.wait() does not exist, use time.sleep(), or the awaitable asyncio.sleep().

import asyncio
import time

async def A():
    time.sleep(1.0)  # blocks, stops B() if called first

async def B():
    await asyncio.sleep(1.0)  # hands back execution, A() can run while timing

async def main():
    t0 = time.time()
    await asyncio.gather(A(), B())           # takes 2 seconds
    print(time.time() - t0)

    t0 = time.time()
    await asyncio.gather(B(), A())           # takes 1 second
    print(time.time() - t0)

if __name__ == '__main__':
    asyncio.run(main())

Upvotes: 1

Related Questions