• 协程嵌套协程


    import asyncio
    import functools
    
    # 第三层协程
    async def test1():
        print('我是test1')
        await asyncio.sleep(1)
        print('test1已经睡了1秒')
        await asyncio.sleep(3)
        print('test1又睡了3秒')
        return 'xiong'
    
    # 第三层协程
    async def test2():
        print('我是test2')
        await asyncio.sleep(2)
        print('test2已经睡了2秒')
        await asyncio.sleep(2)
        print('test2又睡了2秒')
        return 'fan'
    
    # 第三层协程
    async def test3():
        print('我是test3')
        await asyncio.sleep(3)
        print('test3已经睡了3秒')
        await asyncio.sleep(1)
        print('test3又睡了1秒')
        return 'yong'
    
    # 第三层协程
    async def test4():
        print('我是test4')
        await asyncio.sleep(4)
        print('test4已经睡了4秒')
        await asyncio.sleep(1)
        print('test4又睡了1秒')
        return 'fan'
    
    # 协程回调函数
    def callback_test1(name, future):
        print(future.result()[0]+name)
    
    # 第二层协程
    async def main():
        tasks = [
            asyncio.ensure_future(test1()),
            asyncio.ensure_future(test2()),
            asyncio.ensure_future(test3()),
        ]
        res = await asyncio.gather(*tasks)
        return res
    
    # 第二层协程
    async def main1():
        res = await test4()
        return res
    
    # 最外层协程(主入口)
    async def z_main():
        tasks = [
            asyncio.ensure_future(main()),
            asyncio.ensure_future(main1())
        ]
        # 用了偏函数传其他参数
        tasks[0].add_done_callback(functools.partial(callback_test1, 'fanyong'))
        res1 = await asyncio.gather(*tasks)
        return res1
    
    if __name__ == '__main__':
        # tasks = [
        #     asyncio.ensure_future(test1()),
        #     asyncio.ensure_future(test2()),
        #     asyncio.ensure_future(test3()),
        # ]
        # tasks[0].add_done_callback(functools.partial(callback_test1, 'fanyong'))
        loop = asyncio.get_event_loop()
        res2 = loop.run_until_complete(z_main())
        print(res2)
  • 相关阅读:
    自动控制中的泛函分析(一)
    自动控制中的泛函分析(一)
    Andrew Ng机器学习课程15
    Andrew Ng机器学习课程14(补)
    Andrew Ng机器学习课程14(补)
    关于PADS的一些概念和实用技巧(一)
    关于PADS的一些概念和实用技巧(一)
    Andrew Ng机器学习课程14
    Andrew Ng机器学习课程14
    《数学之美》之计算复杂度
  • 原文地址:https://www.cnblogs.com/xiongfanyong/p/13403525.html
Copyright © 2020-2023  润新知