搜尋
首頁後端開發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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版