代码展示 

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()

 

运行效果截图

 

 

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐