async协程嵌套

协程嵌套

import asyncio

import time

now =
lambda: time.time()

async def do_some_work(x):
   
print('Waiting: ', x)

   
await asyncio.sleep(x)
   
return 'Done after {}s'.format(x)
#
将协程的工作内容放进一个函数里,将这个函数添加进事件循环
async def main():
    coroutine1 = do_some_work(
1)
    coroutine2 = do_some_work(
2)
    coroutine3 = do_some_work(
4)

    tasks = [
        asyncio.ensure_future(coroutine1),
        asyncio.ensure_future(coroutine2),
        asyncio.ensure_future(coroutine3)
    ]

    dones, pendings =
await asyncio.wait(tasks)

   
for task in dones:
       
print('Task ret: ', task.result())

start = now()
#
将这个函数添加进事件循环
loop = asyncio.get_event_loop()
loop.run_until_complete(main())


print('TIME: ', now() - start)

你可能感兴趣的:(python_协程)