python里并发执行协程时部分阻塞超时怎么办
2017-09-08 17:39
609 查看
Python游戏开发入门
http://edu.csdn.net/course/detail/5690跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在前面的例子里学习了并发地执行多个协程来下载图片,也许其中一个协程永远下载不了,一直阻塞,这时怎么办呢?碰到这种需求时不要惊慌,可以使用wait()里的timeout参数来设置等待时间,也就是从这个函数开始运行算起,如果时间到达协程没有执行完成,就可以不再等它们了,直接从wait()函数里返回,返回之后就可以判断那些没有执行成功的,可以把这些协程取消掉。例子如下:
import asyncio
async def phase(i):
print('in phase {}'.format(i))
try:
await asyncio.sleep(0.1 * i)
except asyncio.CancelledError:
print('phase {} canceled'.format(i))
raise
else:
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 0.1 for phases to complete')
completed, pending = await asyncio.wait(phases, timeout=0.1)
print('{} completed and {} pending'.format(
len(completed), len(pending),
))
# Cancel remaining tasks so they do not generate errors
# as we exit without finishing them.
if pending:
print('canceling tasks')
for t in pending:
t.cancel()
print('exiting main')
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(3))
finally:
event_loop.close()结果输出如下:starting main
waiting 0.1 for phases to complete
in phase 0
in phase 2
in phase 1
done with phase 0
1 completed and 2 pending
canceling tasks
exiting main
phase 1 canceled
phase 2 canceled
相关文章推荐
- python里创建多个协程并发执行
- Python - 用协程并发执行测试用例
- python里怎么实现多个协程一起执行,只要完成一个就返回一个协程
- python里怎么终止程序的执行
- 使用PyInstaller2将Python脚本转化为可执行文件(上-安装部分)(转载自博客园balian)
- python学习笔记:多并发(线程、进程、协程)
- 使用PyInstaller2将Python脚本转化为可执行文件(上-安装部分)
- 使用PyInstaller2将Python脚本转化为可执行文件(中-使用部分)(转载自博客园balian)
- android中 回调方法,怎么转变为阻塞执行的方法
- 使用PyInstaller2将Python脚本转化为可执行文件(中-使用部分)
- 使用PyInstaller2将Python脚本转化为可执行文件(中-使用部分)
- python基础-协程gevent用法、协程同步异步、协程socket并发例子
- ubuntu上怎么设置默认python命令是执行python3而不是python2
- Python 并发编程之协程/异步IO
- Python2 socket TCPServer 多线程并发 超时关闭
- python并发编程之多进程理论部分
- python并发编程之多进程、多线程、异步和协程
- Python 2.x如何设置命令执行的超时时间实例
- Python并发实践_02_通过yield实现协程
- Python异步非阻塞IO多路复用Select/Poll/Epoll使用,线程,进程,协程