利用multiprocessing創建多進程
阿新 • • 發佈:2018-11-09
() 導入模塊 子進程 pytho target code 豆豆 進程 art
import multiprocessing as mp import os import time #將要做的事封裝為函數 def th1(): print(os.getppid(),"----",os.getpid()) print('吃飯早飯') time.sleep(1) print('吃飯午飯') time.sleep(2) print('吃飯晚飯') time.sleep(3) def th2(): print(os.getppid(),"----",os.getpid()) print("睡午覺") time.sleep(1) print("睡覺") time.sleep(3) def th3(): print(os.getppid(),"----",os.getpid()) print("打豆豆") time.sleep(2) print("打豆豆") time.sleep(2) #創建3個子進程,生成子進程對象 #將函數和進程進行關聯 p1 = mp.Process(target = th1) p2 = mp.Process(target = th2) p3 = mp.Process(target = th3) #啟動進程讓其執行對應的函數事件 #該函數即為這個就進程內容 p1.start() p2.start() p3.start() print("Parent PID:",os.getpid()) # 阻塞等對應子進程的退出,然後回收子進程 p1.join() p2.join() p3.join() print("***********************") # th1() # th2() # th3() #1.導入模塊 #2.創建函數 #3.關聯函數 #4.啟動子進程函數 #5.回收子進程
利用multiprocessing創建多進程