生产者与消费者模型,其实是把一个需要进程通信的问题 分开考虑
生产者,只需要王队列里存任务
消费者,只需要从队列里取任务
多线程版生产者与消费者模式
# -*- 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 = q def run(self): while True: item = self.queue.get() print("消费了", item) if __name__ == "__main__": producer = Producer(q) consumer = Consumer(q) producer.start() consumer.start()
多进程版生产者与消费者模式
# -*- coding: utf-8 -*- """ 进程生产者与消费者模型 """ from multiprocessing import Process, Manager from random import randint # 生产者 class Producer(Process): def __init__(self, q): super().__init__() self.queue = q def run(self): print('?') while True: items = [item for item in range(randint(0, 10))] self.queue.put(items) print("生产了", items) # 消费者 class Consumer(Process): def __init__(self, q): super().__init__() self.queue = q def run(self): while True: items = self.queue.get() print("消费了", items) if __name__ == '__main__': manager = Manager() # q为守护进程,主进程如果先结束了,q就释放了,因此需要主进程等待子进程结束 q = manager.Queue(3) # manager.list() , manager.dict() producer = Producer(q) consumer = Consumer(q) producer.start() consumer.start() producer.join() consumer.join() # input() # 阻塞