代码:
from multiprocessing import Process, Queuedef producer(q):myinfo = "包子"q.put(myinfo)print(f"生产了{myinfo}")myinfo = "饺子"q.put(myinfo)print(f"生产了{myinfo}\n")''' 生产了4个,消费5个 ''' def consumer(q):print(f"消费掉了{q.get()}")print(f"消费掉了{q.get()}")print(f"消费掉了{q.get()}")print(f"消费掉了{q.get()}")print(f"消费掉了{q.get()}")if __name__ == "__main__":q = Queue()p1 = Process(target=producer, args=(q, ))p2 = Process(target=consumer, args=(q, ))print("生产呵呵和哈哈")q.put("呵呵")q.put("哈哈")p1.start()p2.start()p1.join()#p2.join()p2.terminate()
输出:
生产呵呵和哈哈
生产了包子
生产了饺子消费掉了呵呵
消费掉了哈哈
消费掉了包子
消费掉了饺子