在python里使用await关键字来等另外一个协程的实例


Posted in Python onMay 04, 2020

一个协程里可以启动另外一个协程,并等待它完成返回结果,采用await关键字,

例子如下:

import asyncio
 
async def outer():
  print('in outer')
  print('waiting for result1')
  result1 = await phase1()
  print('waiting for result2')
  result2 = await phase2(result1)
  return (result1, result2)
 
async def phase1():
  print('in phase1')
  return 'result1'
 
async def phase2(arg):
  print('in phase2')
  return 'result2 derived from {}'.format(arg)
 
event_loop = asyncio.get_event_loop()
try:
  return_value = event_loop.run_until_complete(outer())
  print('return value: {!r}'.format(return_value))
finally:
  event_loop.close()

输出结果如下:
in outer
waiting for result1
in phase1
waiting for result2
in phase2
return value: ('result1', 'result2 derived from result1')

await关键字添加了一个新的协程到循环里,而不需要明确地添加协程到这个事件循环里。

补充知识:python里使用Condition对象来唤醒指定数量的协程

在asyncio库里,定义Condition对象,它的行为与事件Event有点像,区别是事件是通知所有对象,Condition对象可以指定一定数量的协程被通知,它是通过函数notify()来实现的,如果参数里放2,就是通知两个协程,例子如下:

import asyncio
 
async def consumer(condition, n):
  with await condition:
    print('consumer {} is waiting'.format(n))
    await condition.wait()
    print('consumer {} triggered'.format(n))
  print('ending consumer {}'.format(n))
 
async def manipulate_condition(condition):
  print('starting manipulate_condition')
 
  # pause to let consumers start
  await asyncio.sleep(0.1)
 
  for i in range(1, 3):
    with await condition:
      print('notifying {} consumers'.format(i))
      condition.notify(n=i)
    await asyncio.sleep(0.1)
 
  with await condition:
    print('notifying remaining consumers')
    condition.notify_all()
 
  print('ending manipulate_condition')
 
async def main(loop):
  # Create a condition
  condition = asyncio.Condition()
 
  # Set up tasks watching the condition
  consumers = [
    consumer(condition, i)
    for i in range(5)
  ]
 
  # Schedule a task to manipulate the condition variable
  loop.create_task(manipulate_condition(condition))
 
  # Wait for the consumers to be done
  await asyncio.wait(consumers)
 
event_loop = asyncio.get_event_loop()
try:
  result = event_loop.run_until_complete(main(event_loop))
finally:
  event_loop.close()

结果输出如下:

starting manipulate_condition
consumer 2 is waiting
consumer 3 is waiting
consumer 4 is waiting
consumer 1 is waiting
consumer 0 is waiting
notifying 1 consumers
consumer 2 triggered
ending consumer 2
notifying 2 consumers
consumer 3 triggered
ending consumer 3
consumer 4 triggered
ending consumer 4
notifying remaining consumers
ending manipulate_condition
consumer 1 triggered
ending consumer 1
consumer 0 triggered
ending consumer 0

以上这篇在python里使用await关键字来等另外一个协程的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
理解python多线程(python多线程简明教程)
Jun 09 Python
python 简单的多线程链接实现代码
Aug 28 Python
详解Python中的相对导入和绝对导入
Jan 06 Python
Python使用defaultdict读取文件各列的方法
May 11 Python
在Python中使用AOP实现Redis缓存示例
Jul 11 Python
Python八大常见排序算法定义、实现及时间消耗效率分析
Apr 27 Python
pycharm 主题theme设置调整仿sublime的方法
May 23 Python
基于python log取对数详解
Jun 08 Python
Selenium元素的常用操作方法分析
Aug 10 Python
pandas 快速处理 date_time 日期格式方法
Nov 12 Python
python使用tomorrow实现多线程的例子
Jul 20 Python
使用Python制作一盏 3D 花灯喜迎元宵佳节
Feb 26 Python
python 异步async库的使用说明
May 04 #Python
Python插件机制实现详解
May 04 #Python
python3+selenium获取页面加载的所有静态资源文件链接操作
May 04 #Python
解决IDEA 的 plugins 搜不到任何的插件问题
May 04 #Python
python3 sleep 延时秒 毫秒实例
May 04 #Python
Python并发concurrent.futures和asyncio实例
May 04 #Python
Python 中由 yield 实现异步操作
May 04 #Python
You might like
PHP连接MySQL查询结果中文显示乱码解决方法
2013/10/25 PHP
PHP大批量插入数据库的3种方法和速度对比
2014/07/08 PHP
PHP 前加at符合@的作用解析
2015/07/31 PHP
浅谈ThinkPHP中initialize和construct的区别
2017/04/01 PHP
PHP利用缓存处理用户注册时的邮箱验证,成功后用户数据存入数据库操作示例
2019/12/31 PHP
js 页面刷新location.reload和location.replace的区别小结
2009/12/24 Javascript
jQuery源码分析之Event事件分析
2010/06/07 Javascript
js中的时间转换—毫秒转换成日期时间的示例代码
2014/01/26 Javascript
jQuery实现可编辑的表格实例讲解(2)
2015/09/17 Javascript
Bootstrap学习笔记之环境配置(1)
2016/12/07 Javascript
数组Array的一些方法(总结)
2017/02/17 Javascript
vue.js+Echarts开发图表放大缩小功能实例
2017/06/09 Javascript
详解NODEJS基于FFMPEG视频推流测试
2017/11/17 NodeJs
vue中使用cropperjs的方法
2018/03/01 Javascript
javascript性能优化之分时函数的介绍
2018/03/28 Javascript
npm 常用命令详解(小结)
2019/01/17 Javascript
layui实现数据表格自定义数据项
2019/10/26 Javascript
[01:34]2014DOTA2展望TI 剑指西雅图VG战队专访
2014/06/30 DOTA
[00:27]DOTA2次级职业联赛 - Lilith战队宣传片
2014/12/01 DOTA
python冒泡排序算法的实现代码
2013/11/21 Python
教你用Python脚本快速为iOS10生成图标和截屏
2016/09/22 Python
Python wxPython库消息对话框MessageDialog用法示例
2018/09/03 Python
使用PM2+nginx部署python项目的方法示例
2018/11/07 Python
Python3 pandas 操作列表实例详解
2019/09/23 Python
Python 使用元类type创建类对象常见应用详解
2019/10/17 Python
美国基督教约会网站:ChristianCafe.com
2020/02/04 全球购物
物理教育专业毕业生推荐信
2013/11/03 职场文书
教师自荐信
2013/12/10 职场文书
小松树教学反思
2014/02/11 职场文书
2014年教师业务学习材料
2014/05/12 职场文书
出租房屋协议书
2014/09/14 职场文书
毕业酒会致辞
2015/07/29 职场文书
客户答谢会致辞
2015/07/30 职场文书
MySQL 8.0 Online DDL快速加列的相关总结
2021/06/02 MySQL
用JS创建一个录屏功能
2021/11/11 Javascript
Python面试不修改数组找出重复的数字
2022/05/20 Python