Python multiprocessing.Process
阿新 • • 發佈:2018-12-17
multiprocessing.Process
multiprocessing是python的中的一個多程序管理庫,multiprocessing.Process模組用於建立程序
使用方法:
Process(target=, args=)
- target 要執行的函式
- 傳入函式的引數,必須是 iterable
支援的函式:
- is_alive() 判斷程序是否存活
- run() 建立程序未指定 target ,預設執行run()
- start() 執行程序
- join() 阻塞當前程序,直到等待的程序執行完畢再執行當前
- terminate() 停止程序
示例:
import os from multiprocessing import Process def fun(n): print("number is %d, process id is %d" % (n, os.getpid())) if __name__ == '__main__': print(os.getpid()) five_process = [] for i in range(5): p = Process(target=fun, args=(i, )) p.start() five_process.append(p) for p in five_process: p.join() print("=====end=====")
輸出:
2332
number is 0, process id is 9768
number is 2, process id is 2924
number is 1, process id is 1292
number is 4, process id is 1960
number is 3, process id is 204
=end=