zoukankan      html  css  js  c++  java
  • python 协程嵌套

    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)
    
    如果使用的是 asyncio.gather创建协程对象,那么await的返回值就是协程运行的结果。
    
        results = await asyncio.gather(*tasks)
    
        for result in results:
            print('Task ret: ', result)
    
  • 相关阅读:
    Kubernetes之Replica Set
    Kubernetes之Replication Controller
    Kubernetes之Deployment
    golang channel select
    golang slice
    epoll的由来
    ceph crush 之 crush_do_rule
    libevent
    P2P资料
    混沌理论学习笔记
  • 原文地址:https://www.cnblogs.com/c-x-a/p/9333883.html
Copyright © 2011-2022 走看看