python 多進程multiprocessing 模塊

multiprocessing 經常使用方法:

  • cpu_count():統計cpu核數python

    multiprocessing.cpu_count()less

  • active_children() 獲取全部子進程函數

    multiprocessing.active_children()spa

  • preces() 建立一個進程對象code

    multiprocessing.Preces(target=function_name, args=())對象

    target: 函數名  args: 函數須要的參數,以tuple形式傳入,一個參數時需(1,)

Preces 經常使用方法:

  • is_alive() 判斷進程是否存在進程

  • run() 啓動進程ip

  • start() 啓動進程,會自動調用run方法,這個經常使用get

  • 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 進程名子string

  • pid 進程的pid

相關文章
相關標籤/搜索