python里怎么实现多个协程一起执行,只要完成一个就返回一个协程
2023-09-14 09:10:35 时间
需要使用新的函数as_completed()来实现,可以把多个并发的协程一起给它,但它把返回的结果变成一个生成器,每次返回一个协程的结果,与函数wait()一样,执行协程是乱序的,不会等所有协程执行完成才返回。例子:
import asyncio
async def phase(i):
print('in phase {}'.format(i))
await asyncio.sleep(0.5 - (0.1 * i))
print('done with phase {}'.format(i))
return 'phase {} result'.format(i)
async def main(num_phases):
print('starting main')
phases = [
phase(i)
for i in range(num_phases)
]
print('waiting for phases to complete')
results = []
for next_to_complete in asyncio.as_completed(phases):
answer = await next_to_complete
print('received answer {!r}'.format(answer))
results.append(answer)
print('results: {!r}'.format(results))
return results
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(3))
finally:
event_loop.close()
结果输出如下:
starting main
waiting for phases to complete
in phase 2
in phase 1
in phase 0
done with phase 2
received answer 'phase 2 result'
done with phase 1
received answer 'phase 1 result'
done with phase 0
received answer 'phase 0 result'
results: ['phase 2 result', 'phase 1 result', 'phase 0 result']
Python游戏开发入门
你也能动手修改C编译器
纸牌游戏开发
http://edu.csdn.net/course/detail/5538
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672
相关文章
- Python: 执行系统命令的四种方法(os.system、os.popen、commands、subprocess)
- Python执行时间的计算方法小结
- python中的subprocess.Popen() 执行shell命令
- python 在cmd时执行celery -A tasks worker --loglevel=info报错:failed to create process怎么解决
- Python操作符重载
- python执行shell命令四法
- Python 调试方法
- 【python】一次执行多个linux命令
- paip.执行shell cmd 命令uapi java php python总结
- paip.python 执行shell 带空格命令行attilax总结
- 华为OD机试 - 简单的解压缩算法(Java & JS & Python)
- 成功解决mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is de
- Python编程:Celery执行异步任务和定时任务
- python 匿名函数捕获变量值 (执行时的值)
- 利用pyinstaller发布不依赖python解释器的可执行exe
- linux下执行python 提示module找不到 要加入系统路劲才找得到
- python装饰器执行顺序
- SikuliX----SikuliX生成的脚本使用Python调用执行
- Python 封装SNMP调用接口
- python super 理解(一)