搜索
首页后端开发Python教程异步事件和条件:Python 交通信号的秘密生活

Asyncio Events and Conditions: The Secret Life of Python

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

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

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


import asyncio

async 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())。

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


import asyncio

async 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 asyncio

async 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 的工作原理有了更清晰的了解。他们是幕后协调员,确保一切顺利进行。

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

以上是异步事件和条件:Python 交通信号的秘密生活的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
python中两个列表的串联替代方案是什么?python中两个列表的串联替代方案是什么?May 09, 2025 am 12:16 AM

可以使用多种方法在Python中连接两个列表:1.使用 操作符,简单但在大列表中效率低;2.使用extend方法,效率高但会修改原列表;3.使用 =操作符,兼具效率和可读性;4.使用itertools.chain函数,内存效率高但需额外导入;5.使用列表解析,优雅但可能过于复杂。选择方法应根据代码上下文和需求。

Python:合并两个列表的有效方法Python:合并两个列表的有效方法May 09, 2025 am 12:15 AM

有多种方法可以合并Python列表:1.使用 操作符,简单但对大列表不内存高效;2.使用extend方法,内存高效但会修改原列表;3.使用itertools.chain,适用于大数据集;4.使用*操作符,一行代码合并小到中型列表;5.使用numpy.concatenate,适用于大数据集和性能要求高的场景;6.使用append方法,适用于小列表但效率低。选择方法时需考虑列表大小和应用场景。

编译的与解释的语言:优点和缺点编译的与解释的语言:优点和缺点May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:对于循环,最完整的指南Python:对于循环,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循环用于遍历可迭代对象,while循环用于条件满足时重复执行操作。1)for循环示例:遍历列表并打印元素。2)while循环示例:猜数字游戏,直到猜对为止。掌握循环原理和优化技巧可提高代码效率和可靠性。

python concatenate列表到一个字符串中python concatenate列表到一个字符串中May 09, 2025 am 12:02 AM

要将列表连接成字符串,Python中使用join()方法是最佳选择。1)使用join()方法将列表元素连接成字符串,如''.join(my_list)。2)对于包含数字的列表,先用map(str,numbers)转换为字符串再连接。3)可以使用生成器表达式进行复杂格式化,如','.join(f'({fruit})'forfruitinfruits)。4)处理混合数据类型时,使用map(str,mixed_list)确保所有元素可转换为字符串。5)对于大型列表,使用''.join(large_li

Python的混合方法:编译和解释合并Python的混合方法:编译和解释合并May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

了解python的' for”和' then”循环之间的差异了解python的' for”和' then”循环之间的差异May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串联列表与重复Python串联列表与重复May 08, 2025 am 12:09 AM

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境