import timeimport randomfrom multiprocessing import Queue # 生产者def producer(q, num): for i in range(1, num + 1): food = ‘Spam-%d‘ % i # time.sleep(random.uniform(1, 2)) timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(‘时间:%s\t生产者:%d 生产了 %d‘ % (timeVal, i, i)) q.put(food) # 消费者def consumer(q): while True: food = q.get() if not food: break # time.sleep(random.uniform(1, 2)) timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(‘时间:%s\t消费者吃了 %s‘ % (timeVal, food)) if __name__ == ‘__main__‘: q = Queue() num = 50 # 生产者 producer(q, num) q.put(None) # 消费者 consumer(q) print(‘end‘)
原文地址:https://www.cnblogs.com/WebLinuxStudy/p/11776715.html
时间: 2024-10-11 12:25:48