Python simple to use asynchronous coroutine

Code

import asyncio


async def ex(id, n):
    print(id+" start")
    await asyncio.sleep(n/2)
    print(id+" 1/2")
    await asyncio.sleep(n/2)
    print(id+" 2/2")
    return n + 1


async def go():
    c1 = ex("one", 4)
    c2 = ex("two", 6)
    await asyncio.gather(c1, c2)

g = go()
asyncio.run(g)

result

one start
two start
one 1/2
two 1/2
one 2/2
two 2/2

Guess you like

Origin www.cnblogs.com/boxker/p/11799556.html