問題描述:
最近遇到這樣一個問題,要求使用 Python3 ,開辟一個程序池,裡面放一個生産者程序,然後其他的都是消費者程序,程序間用 Queue() 進行通信。
問題分析:
問題很好解決,但是要注意一點,就是在使用 Python 的程序池 Pool() 時,Queue() 可能會出錯,需要使用 Manager().Queue(), 算是一個坑吧哈,現在總結一下。
Python3實作:
# @Time :2018/08/30
# @Author :LiuYinxing
from multiprocessing import Pool, Manager
import os, time, random
def Producer(q): # 生産者程序
for i in range(50):
print('生産者程序', os.getpid(), '寫入隊列Q:', i)
q.put(i)
def Consumer(q): # 消費者程序
while True:
time.sleep(random.random() * 2)
try:
print('消費者程序', os.getpid(), '從隊列Q讀出:', q.get(timeout=5))
except:
print('消費者程序', os.getpid(), '等待時間過長終止')
break
if __name__=='__main__':
print('父程序 id:', os.getpid())
q = Manager().Queue() # 建立 隊列
p = Pool(4) # 建立一個程序池
p.apply_async(Producer, args=(q,)) # 向程序池添加程序
for i in range(5):
p.apply_async(Consumer, args=(q,))
print('等待所有子程序準備完成...')
p.close() # 不能再添加程序了
p.join()
print('所有程序完成任務...')