1. 程式人生 > >Python生產者消費者模型

Python生產者消費者模型

bsp 圖片 sch Coding print gpo con targe int

用多線程和隊列來實現生產者消費者模型

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import queue
import time

q = queue.Queue()

def Producer(name):
    count = 1
    while True:
        q.put("面包%s" %count)
        print("[%s]做了[%s]個面包" %(name,count))
        count +=1
        time.sleep(1)

def Consumer(name):
    while True:
        print("[%s]取得[%s]並吃了它" %(name,q.get()))
        time.sleep(1)

t1 = threading.Thread(target=Producer,args=("掌櫃",))
t2 = threading.Thread(target=Consumer,args=("張三",))
t3 = threading.Thread(target=Consumer,args=("李四",))

t1.start()
t2.start()
t3.start()

運行結果

技術分享圖片

生產一個消費一個,兩個消費者是按照順序一個一個地消費

Python生產者消費者模型