from multiprocessing import Process, Queue,Pool import time import os def producer(q): for i in range(5): time.sleep(0.6) print("生產第%s個包子" % (i + 1)) res = i + 1 q.put(res) # 沒生產一個,往隊列里加一個 time.sleep(1) q.put(None) def cousumer(q): while True: res = q.get() if res == None: break time.sleep(1) print("消費者吃的第%s個包子" % res) if __name__ == '__main__': ''' 進程: target:表示調用對象,也就是子進程要執行的對象 args:調用對象的位置參數元組 kwargs:調用對象的字典 name:子進程的名字 p.join([timeout]):主線程等待P終止 進程隊列:進程彼此隔離,要實現進程之間的通訊,能夠使用隊列和管道 q = Queue([maxsize]) q.put('123') #往隊列中加元素 q.get('123') #往隊列中讀取並刪除一個元素 q.full() #判斷隊列是否已經滿了,滿了再放進去就會阻塞 q.empty() #判斷隊列是否已經空了,空了就不能再get ''' q = Queue() p_lst = [] for i in range(5): s1 = "子進程" + "producer" s2 = "子進程" + "cousumer" p = Process(target=producer, args=(q,), name=s1) c = Process(target=cousumer, args=(q,), name=s2) p.start() c.start() print(p.pid) p_lst.append(p) print(p.is_alive()) # 判斷進程P是否存話 # p.terminate() # 終止P進程 print(p.is_alive()) p.join() ''' 須要等待子進程執行完畢後才能繼續執行,就須要有一種機制可以讓主進程檢測子進程是否運行完畢,在子進程執行完畢後才繼續執行,不然一直在原地阻塞,這就是join方法的做用 看清楚:join做用是讓主進程等待子進程結束,其餘子進程並不會中止 ''' time.sleep(1) print("執行主進程") print(p_lst)