Python中協(xié)程間通信的方式小結(jié)
在 Python 中,協(xié)程間的通信主要依賴于以下幾種方式:
1. asyncio.Queue
asyncio.Queue
是 Python asyncio
庫提供的一個(gè)線程安全的隊(duì)列,用于在協(xié)程之間傳遞數(shù)據(jù)。與常規(guī)的隊(duì)列類似,但它支持異步操作,即可以在協(xié)程內(nèi)等待隊(duì)列中的數(shù)據(jù)。
示例:
import asyncio async def producer(queue): for i in range(5): await queue.put(i) print(f"Produced: {i}") await asyncio.sleep(1) async def consumer(queue): while True: item = await queue.get() if item is None: # 用 None 表示終止信號(hào) break print(f"Consumed: {item}") await asyncio.sleep(2) async def main(): queue = asyncio.Queue() await asyncio.gather(producer(queue), consumer(queue)) asyncio.run(main())
2. asyncio.Event
asyncio.Event
是一個(gè)簡單的同步原語,允許一個(gè)協(xié)程等待某個(gè)事件的發(fā)生,另一個(gè)協(xié)程則負(fù)責(zé)設(shè)置該事件。通常用于通知其他協(xié)程某些狀態(tài)發(fā)生變化。
示例:
import asyncio async def waiter(event): print("Waiting for event...") await event.wait() # 阻塞直到事件被觸發(fā) print("Event occurred!") async def setter(event): await asyncio.sleep(2) print("Setting event!") event.set() # 設(shè)置事件 async def main(): event = asyncio.Event() await asyncio.gather(waiter(event), setter(event)) asyncio.run(main())
3. asyncio.Condition
asyncio.Condition
類似于線程中的 Condition
,允許一個(gè)或多個(gè)協(xié)程等待某個(gè)條件的變化。它可以與鎖結(jié)合使用。
示例:
import asyncio async def consumer(condition, shared_data): async with condition: while shared_data["item"] is None: await condition.wait() # 等待條件 print(f"Consumed: {shared_data['item']}") shared_data["item"] = None async def producer(condition, shared_data): await asyncio.sleep(1) async with condition: shared_data["item"] = "Apple" condition.notify() # 通知等待的協(xié)程 print(f"Produced: {shared_data['item']}") async def main(): shared_data = {"item": None} condition = asyncio.Condition() await asyncio.gather(producer(condition, shared_data), consumer(condition, shared_data)) asyncio.run(main())
4. asyncio.Semaphore
asyncio.Semaphore
是一個(gè)計(jì)數(shù)信號(hào)量,控制并發(fā)訪問的協(xié)程數(shù)目。適用于限制協(xié)程的并發(fā)數(shù)量。
示例:
import asyncio async def task(sem): async with sem: print("Task started") await asyncio.sleep(1) print("Task completed") async def main(): sem = asyncio.Semaphore(2) # 最多同時(shí)運(yùn)行2個(gè)協(xié)程 tasks = [task(sem) for _ in range(5)] await asyncio.gather(*tasks) asyncio.run(main())
5. asyncio.Streams (StreamReader 和 StreamWriter)
StreamReader
和 StreamWriter
是用于網(wǎng)絡(luò)通信的流接口,適用于兩個(gè)協(xié)程之間通過網(wǎng)絡(luò)協(xié)議傳輸數(shù)據(jù)的場景。盡管它們主要用于處理網(wǎng)絡(luò) I/O,但也可以用于在協(xié)程之間傳輸數(shù)據(jù)。
示例:
import asyncio async def echo(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print("Send: %r" % message) writer.write(data) await writer.drain() print("Closing the connection") writer.close() async def main(): server = await asyncio.start_server( echo, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever() asyncio.run(main())
6. asyncio.Future
asyncio.Future
類似于 Promise
,它表示一個(gè)尚未完成的操作。一個(gè)協(xié)程可以將其結(jié)果存儲(chǔ)在 Future
對(duì)象中,而其他協(xié)程可以等待該 Future
對(duì)象完成。
示例:
import asyncio async def set_future(future): await asyncio.sleep(1) future.set_result('Hello from Future!') async def get_future(future): result = await future print(f"Got result: {result}") async def main(): future = asyncio.Future() await asyncio.gather(set_future(future), get_future(future)) asyncio.run(main())
這些通信方式各有其特定的用途,可以根據(jù)不同的場景選擇合適的方式來進(jìn)行協(xié)程間的通信。
到此這篇關(guān)于Python中協(xié)程間通信的方式小結(jié)的文章就介紹到這了,更多相關(guān)Python 協(xié)程間通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3中條件控制、循環(huán)與函數(shù)的簡易教程
這篇文章主要給大家介紹了關(guān)于Python3中條件控制、循環(huán)與函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11python實(shí)現(xiàn)啟動(dòng)一個(gè)外部程序,并且不阻塞當(dāng)前進(jìn)程
這篇文章主要介紹了python實(shí)現(xiàn)啟動(dòng)一個(gè)外部程序,并且不阻塞當(dāng)前進(jìn)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12Python OpenCV實(shí)現(xiàn)裁剪并保存圖片
這篇文章主要為大家詳細(xì)介紹了Python OpenCV實(shí)現(xiàn)裁剪并保存圖片,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07深入淺析Python 函數(shù)注解與匿名函數(shù)
這篇文章主要介紹了Python 函數(shù)注解與匿名函數(shù)的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02python+Splinter實(shí)現(xiàn)12306搶票功能
這篇文章主要為大家詳細(xì)介紹了python+Splinter實(shí)現(xiàn)12306搶票功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09利用Python判斷整數(shù)是否是回文數(shù)的3種方法總結(jié)
這篇文章主要給大家介紹了關(guān)于如何利用Python判斷整數(shù)是否是回文數(shù)的3種方總結(jié),回文數(shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù),需要的朋友可以參考下2021-07-07Python實(shí)現(xiàn)文件操作幫助類的示例代碼
在使用Python進(jìn)行業(yè)務(wù)開發(fā)的時(shí)候,需要將一些數(shù)據(jù)保存到本地文件存儲(chǔ),方便后面進(jìn)行數(shù)據(jù)分析展示,本文就來用Python制作一個(gè)文件操作幫助類,需要的可以參考一下2023-03-03