当前位置 博文首页 > 小航冲冲冲的博客:python进程实现生产者消费者模型
from multiprocessing import Process, Queue
import time
def producer(q, name, food, shi):
count = 1
while True:
res = f"{food}{count}"
time.sleep(shi)
q.put(res)
print(f"{time.strftime('%H:%M-%S')} {name}:生产了:{res}")
count += 1
def consumer(q, name, shi):
while True:
res = q.get()
time.sleep(shi)
print(f"{time.strftime('%H:%M-%S')} {name}:吃了:{res}")
if __name__ == "__main__":
q = Queue(maxsize=10)
p1 = Process(target=producer, args=(q, "B", "冷饮", 2))
p2 = Process(target=producer, args=(q, "E", "冰淇淋", 3))
c1 = Process(target=consumer, args=(q, "A", 4))
c2 = Process(target=consumer, args=(q, "C", 5))
c3 = Process(target=consumer, args=(q, "D", 6))
p1.start()
p2.start()
c1.start()
c2.start()
c3.start()
p1.join()
p2.join()
?
?
?