7/13/2021python 核心程式設計02-02-15
阿新 • • 發佈:2021-07-13
生產者與消費者的解耦問題:
耦合時程式碼之前聯絡性很強,不好
解耦: 減少之間的聯絡
所以第一版本就要想的長遠一點
這個例子使用佇列作為緩衝部分
#encoding=utf-8
import threading
import time
from queue import Queue
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize()<1000:
count = count +1
msg = '生產產品'+str(count)
queue.put(msg)
print(msg)
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize()>100:
for i in range(3):
msg = self.name +'消費了'+queue.get()
print(msg)
time.sleep(1)
if __name__ == "__main__":
queue = Queue()
for i in range(500):
queue.put("初始產品"+str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()