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



原创粉丝点击