【作業系統實驗】python程式碼模擬實現生產者消費者模式
阿新 • • 發佈:2018-12-22
相比C/C++指標的折磨,本人更喜歡python程式碼的簡潔,廢話不多說:
from multiprocessing import Process, JoinableQueue
import time, random, os
def consumer(q):
while True:
res = q.get()
time.sleep(random.randint(1, 3))
print('%s 吃 %s' % (os.getpid(), res))
q.task_done() # 向q.join()傳送一次訊號,證明一個數據已經被取走了
def producer(name, q):
for i in range(10):
time.sleep(random.randint(1, 3))
res = '%s%s' % (name, i)
q.put(res)
print('%s 生產了 %s' % (os.getpid(), res))
q.join()
if __name__ == '__main__':
q = JoinableQueue() # 類似Queue佇列 多了task
# 生產者們:即廚師們
p1 = Process(target=producer, args=('~~魚香雞蛋~~', q))
p2 = Process( target=producer, args=('~~麻辣豆腐~~', q))
p3 = Process(target=producer, args=('~~土豆炒肉~~', q))
# 消費者們:即吃貨們
c1 = Process(target=consumer, args=(q,))
c2 = Process(target=consumer, args=(q,))
c1.daemon = True # c1 c2 設定為守護程序
c2.daemon = True
# 開始
p_l = [p1, p2, p3, c1, c2]
for p in p_l:
p.start( )
p1.join()
p2.join()
p3.join()
print('主')
# 主程序等--->p1,p2,p3等---->c1,c2
# p1,p2,p3結束了,證明c1,c2肯定全都收完了p1,p2,p3發到佇列的資料
# 因而c1,c2也沒有存在的價值了,應該隨著主程序的結束而結束,所以設定成守護程序