python里创建多个协程并发执行
来源:互联网 发布:怿不甚知书 编辑:程序博客网 时间:2024/05/23 11:56
像前面线性地执行的协程,理解起来非常容易,并且使用关键字await就可以解决了,但是很多情况之下是并发地执行多个协程的,因为常常把任务分解成多个协程运行,比如要从一个网站上下载网页,这时需要下载HTML内容,同时也要下载网页里很多图片的资源,在这种情况之下,就可以把多个图片下载进行并发执行,并且没有顺序运行的关系。在这个例子里使用wait()函数来实现多个协程并发执行,并等待所有协程完成:
import asyncioasync def phase(i): print('in phase {}'.format(i)) await asyncio.sleep(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') completed, pending = await asyncio.wait(phases) results = [t.result() for t in completed] print('results: {!r}'.format(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 0
in phase 2
in phase 1
done with phase 0
done with phase 1
done with phase 2
results: ['phase 2 result', 'phase 0 result', 'phase 1 result']
在这个例子里,使用wait()函数来等所有协程完成,返回两个结果集的元组:完成和阻塞的作务。
Python游戏开发入门
http://edu.csdn.net/course/detail/5690
你也能动手修改C编译器
http://edu.csdn.net/course/detail/5582
纸牌游戏开发
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
阅读全文
0 0
- python里创建多个协程并发执行
- python里怎么实现多个协程一起执行,只要完成一个就返回一个协程
- python实现多个协程协作
- python里使用await关键字来等另外一个协程
- python里创建任务执行一半时取消任务执行
- python里并发执行协程时部分阻塞超时怎么办
- WCF多个协定实现
- python 并发执行
- Python并发执行
- 多个协程的调用顺序,以及Update和Start的关系
- python里仅收集所有协程执行结果
- Python concurent Execution(Python 并发执行)
- 并发编程--创建线程执行器
- python多线程并发执行程序实战讲解
- python里怎么终止程序的执行?
- python里怎么终止程序的执行
- 一个协程的使用示例(走走停停效果)
- 传说中的WCF(3):多个协定
- 智能天线调试助手之RFFE协议模拟
- 第十一章——编辑UITableView
- lseek 在结尾添加数据
- linux下查看文件第20-30行内容的N种方法及命令介绍
- POJ 3111 最大化平均值
- python里创建多个协程并发执行
- JVM内存问题Error occurred during initialization of VM
- vue2.0组件之间的通信
- java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException
- jenkins整合tomcat进行持续deploy
- C/C++:随机数生成
- Android基础技术核心归纳(四)
- Useful JVM Flags – Part 7 (CMS Collector)
- 搭载SSR && BBR