multiprocessing 常用方法:
-
cpu_count():統計cpu核數
multiprocessing.cpu_count()
-
active_children() 獲取所有子進程
multiprocessing.active_children()
-
preces() 創建一個進程對象
multiprocessing.Preces(target=function_name, args=())
target: 函數名 args: 函數需要的參數,以tuple形式傳入,一個參數時需(1,)
Preces 常用方法:
-
is_alive() 判斷進程是否存在
-
run() 啟動進程
-
start() 啟動進程,會自動調用run方法,這個常用
-
join([timeout]) 等待進程結束或者直到超時
- join() 方法說明:
def def worker(interval): time.sleep(interval) print('hello world') P = multiprocessing.Process(target=worker, args=(5,)) #----------------------------------- P.start() #設置timeout 設置超時時間 print(P.is_alive()) P.join(timeout=3) print('end main') ### True end main hello world #----------------------------------- P.start() P.alive() # 不調置timeout 超時時間 P.join() print() ### True hello world end main #----------------------------------- 結論: 當join()不設置timeout時程序會一直等待上面的進程執行完成后再執行join()后面的代碼 當設置timeout時,無論上面的進程是否執行完成,程序運行到指定時間后就會執行后面的代碼
Preces 常用屬性
-
namd 進程名子
-
pid 進程的pid