多进程实现生产者消费者
1 # 多进程实现生产者消费者模型 2 import multiprocessing 3 import random 4 import time 5 6 7 class Producer(multiprocessing.Process): 8 def __init__(self, que): 9 super().__init__() 10 self.que = que 11 12 def run(self): 13 while True: 14 data = random.randint(0, 100) 15 print("生产者生产了:", data) 16 self.que.put(data) 17 time.sleep(1) 18 19 20 class Consumer(multiprocessing.Process): 21 def __init__(self, que): 22 super().__init__() 23 self.que = que 24 25 def run(self): 26 while True: 27 item = self.que.get() 28 print("消费者消费了:", item) 29 30 31 if __name__ == '__main__': 32 q = multiprocessing.Manager().Queue() 33 pro = Producer(q) 34 pro.start() 35 con = Consumer(q) 36 con.start() 37 pro.join()