Python3 基於協程asyncio的消費者模式

注意本例運行在Linux環境下
本例模擬一個生產者每2-4秒生成一個消息,然後有多個消費者消費這些消息。
暫定每個消費者消費一個消息耗時10秒,這樣可以使每個消費者都能消費消息

import time
import asyncio
import queue
import threading
import uuid
import random
'''
基於協程的消費者模型,多個協程充當worker消費消息。
'''

now = lambda : time.time()

async def customer(num,q):
    print('任務 %d:start worker...' % num)
    while True:
        try:
            start = now()
            task = q.get(block=False)
            print('任務 %d:customer %s' % (num, task))
            await asyncio.sleep(10) # 假設每個消費者消費消息需要10秒,這樣可以看出生產者生成的消息被不同的消費者消費
        except Exception as e:
            await asyncio.sleep(1)
            continue


async def run_async_customer(q):
    tasks = []
    for num in range(3):
        tasks.append(asyncio.create_task(customer(num,q)))
    await asyncio.gather(*tasks)

def product(q):
    print('product start...')
    while True:
        pro = '產品 %s' % str(uuid.uuid1())
        print(pro)
        q.put(pro)
        time.sleep(random.randint(2,4))

def run(q):
    asyncio.run(run_async_customer(q))


if __name__ == '__main__':
    q = queue.Queue()
    # 開啓一個線程運行生產者
    prod = threading.Thread(target=product, args=(q,))
    # 開啓一個線程運行所有的消費者
    cust = threading.Thread(target=run, args=(q,))
    prod.start()
    cust.start()
    prod.join()
    cust.join()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章