PHP前端开发

异步事件和条件:Python 交通信号的秘密生活

百变鹏仔 4天前 #Python
文章标签 信号

有没有想过你的 python 协程如何能够在不造成交通拥堵的情况下很好地协同工作?让我们深入了解异步事件和条件的异想天开的世界 - 防止异步代码变成马戏团的无名英雄(除非您愿意)。

活动:大家都在等待的绿灯
将 asyncio.event 视为代码中的红绿灯。协程排队并耐心(或不那么耐心)等待灯变绿,然后再缩小。

想象一下你和一群人(协程)在人行横道上。行人信号灯是红色的(事件未设置),所以每个人都在等待。当它变成绿色的那一刻(event.set()),整个小组一致前进。没有人愿意成为那个因为闯红灯而躲避汽车的人。

import asyncioasync def pedestrian(event):    print("pedestrian is waiting for the signal.")    await event.wait()    print("pedestrian crosses the street.")async def traffic_light(event):    print("traffic light is red.")    await asyncio.sleep(2)    event.set()    print("traffic light turns green.")async def main():    event = asyncio.event()    await asyncio.gather(pedestrian(event), traffic_light(event))asyncio.run(main())

输出:

pedestrian is waiting for the signal.traffic light is red.traffic light turns green.pedestrian crosses the street.

条件:俱乐部 vip 通行证
asyncio.condition 就像高级俱乐部的保镖。你不仅需要俱乐部开放(有条件),还需要满足一定的条件(await condition.wait())。

尝试进入时尚夜总会的照片。俱乐部(条件)容量有限,只有当其他人离开(满足条件)时,保镖才允许您进入。您可能会在外面等待,练习您最好的舞蹈动作(或尴尬地查看手机),直到获得认可。

立即学习“Python免费学习笔记(深入)”;

import asyncioasync def clubber(condition, name):    async with condition:        print(f"{name} wants to enter the club.")        await condition.wait()        print(f"{name} enters the club.")async def bouncer(condition):    await asyncio.sleep(2)    async with condition:        print("bouncer signals someone can enter.")        condition.notify()async def main():    condition = asyncio.condition()    await asyncio.gather(        clubber(condition, "alice"),        clubber(condition, "bob"),        bouncer(condition)    )asyncio.run(main())

输出:

alice wants to enter the club.bob wants to enter the club.bouncer signals someone can enter.alice enters the club.

在此示例中,只有一名俱乐部成员可以进入俱乐部,因为保镖只向一个人发出信号 (condition.notify())。另一名俱乐部成员仍在无限期地等待。如果你想让每个人都进来(聚会时间!),你可以使用condition.notify_all()。

import asyncioasync def clubber(condition, name):    async with condition:        print(f"{name} wants to enter the club.")        await condition.wait()        print(f"{name} enters the club.")async def bouncer(condition):    await asyncio.sleep(2)    async with condition:        print("bouncer signals everyone can enter.")        condition.notify_all()async def main():    condition = asyncio.condition()    await asyncio.gather(        clubber(condition, "alice"),        clubber(condition, "bob"),        bouncer(condition)    )asyncio.run(main())

输出:

Alice wants to enter the club.Bob wants to enter the club.Bouncer signals everyone can enter.Alice enters the club.Bob enters the club.

聚会结束
现在,您应该对 asyncio eventsconditions 的工作原理有了更清晰的了解。他们是幕后协调者,确保一切顺利进行。

所以,下次当你的异步代码不再像高速公路上的撞车事故时,你就知道该感谢谁了!