消費者與生產者模式的概念
阿新 • • 發佈:2019-04-01
str 需要 rand threading 是把 consumer bsp odin span
生產者與消費者模型,其實是把一個需要進程通信的問題 分開考慮
生產者,只需要王隊列裏存任務
消費者,只需要從隊列裏取任務
多線程版生產者與消費者模式
# -*- coding: utf-8 -*- """ 生產者與消費者模型 """ from threading import Thread from queue import Queue from random import randint q = Queue(4) # 生產者 class Producer(Thread): def __init__(self, q): super().__init__() self.queue = q def run(self): while True: item = randint(0, 100) self.queue.put(item) print("生產了", item) # 消費者 class Consumer(Thread): def __init__(self, q): super().__init__() self.queue = qdef run(self): while True: item = self.queue.get() print("消費了", item) if __name__ == "__main__": producer = Producer(q) consumer = Consumer(q) producer.start() consumer.start()
消費者與生產者模式的概念