asyncio的關鍵字說明
- event_loop事件循環:程序開啟一個無限循環,把一些函數注冊到事件循環上,當滿足事件發生的時候,調用相應的協程函數
- coroutine協程:協程對象,指一個使用async關鍵字定義的函數,它的調用不會立即執行函數,而是會返回一個協程對象,協程對象需要注冊到事件循環,由事件循環調用。
- task任務:一個協程對象就是一個原生可以掛起的函數,任務則是對協程進一步封裝,其中包含了任務的各種狀態
- future:代表將來執行或沒有執行的任務結果。它和task上沒有本質上的區別
- async/await關鍵字:async定義一個協程,await用于掛起阻塞的異步調用接口,在python3.4是使用asyncio.coroutine/yield from
在設計模式中,生產消費者模型占有非常重要的地位,這個模型在現實世界中也有很多有意思的對應場景,比如做包子的人和吃包子的人,當兩者速度不匹配時,就需要有一個模型來做匹配(偶合),實現做的包子都會依次消費掉。
import asyncio
class ConsumerProducerModel:
def __init__(self, producer, consumer, queue=asyncio.Queue(), plate_size=6): # the plate holds 6pcs bread
self.queue = queue
self.producer = producer
self.consumer = consumer
self.plate_size = plate_size
async def produce_bread(self):
for i in range(self.plate_size):
bread = f"bread {i}"
await asyncio.sleep(0.5) # bread makes faster, 0.5s/pc
await self.queue.put(bread)
print(f'{self.producer} makes {bread}')
async def consume_bread(self):
while True:
bread = await self.queue.get()
await asyncio.sleep(1) # eat slower, 1s/pc
print(f'{self.consumer} eats {bread}')
self.queue.task_done()
async def main():
queue = asyncio.Queue()
cp1 = ConsumerProducerModel("John", "Grace", queue) # group 1
cp2 = ConsumerProducerModel("Mike", "Lucy", queue) # group 2
producer_1 = cp1.produce_bread()
producer_2 = cp2.produce_bread()
consumer_1 = asyncio.ensure_future(cp1.consume_bread())
consumer_2 = asyncio.ensure_future(cp2.consume_bread())
await asyncio.gather(*[producer_1, producer_2])
await queue.join()
consumer_1.cancel()
consumer_2.cancel()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
生產消費者模型可以使用多線程和隊列來實現,這里選擇協程不僅是因為性能不錯,而且整個下來邏輯清晰:
1. 先定義初始化的東西,要有個隊列,要有生產者,要有消費者,要有裝面包的盤子大小;
2. 生產者:根據盤子大小生產出對應的東西(面包),將東西放入盤子(queue);
3. 消費者:從盤子上取東西,每次取東西都是一個任務,每次任務完成,就標記為task_done(調用函數)。在這個層面,一直循環;
4. 主邏輯:實例化生產消費者模型對象,創建生產者協程,創建任務(ensure_future),收集協程結果,等待所有線程結束(join),手動取消兩個消費者協程;
5. 運行:首先創建事件循環,然后進入主邏輯,直到完成,關閉循環。
到此這篇關于Python Asyncio模塊實現的生產消費者模型的方法的文章就介紹到這了,更多相關Python生產消費者模型內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python asyncio 協程庫的使用
- python 使用事件對象asyncio.Event來同步協程的操作
- python中asyncio異步編程學習
- python中使用asyncio實現異步IO實例分析
- Python并發concurrent.futures和asyncio實例
- Python中asyncio模塊的深入講解
- Python中的asyncio代碼詳解
- Python中asyncio與aiohttp入門教程
- Python中使用asyncio 封裝文件讀寫
- Python協程asyncio模塊的演變及高級用法