admin管理员组文章数量:1599541
在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游戏开发入门
http://edu.csdn/course/detail/5690你也能动手修改C编译器
http://edu.csdn/course/detail/5582纸牌游戏开发
http://edu.csdn/course/detail/5538
五子棋游戏开发
http://edu.csdn/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn/course/detail/5246
WiX安装工具的使用
http://edu.csdn/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn/course/detail/5110
boost库入门基础
http://edu.csdn/course/detail/5029
Arduino入门基础
http://edu.csdn/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn/course/detail/4810
TensorFlow API攻略
http://edu.csdn/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn/course/detail/4369
C++标准模板库从入门到精通
http://edu.csdn/course/detail/3324
跟老菜鸟学C++
http://edu.csdn/course/detail/2901
跟老菜鸟学python
http://edu.csdn/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn/course/detail/2590
在Windows下SVN的版本管理与实战
http://edu.csdn/course/detail/2579
Visual Studio 2015开发C++程序的基本使用
http://edu.csdn/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn/course/detail/2672
版权声明:本文标题:python里使用Condition对象来唤醒指定数量的协程 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1728324377a1154241.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论