Python 實現多進程的方式主要有兩種,一種方法是使用 os 模塊的 fork 方法,另一種是使用 multiprocessing 模塊。
區別:os.fork 適用於nuix/linux操作系統,不適用於windows系統,multiprocessing 跨平臺。
1、使用os.fork方式實現多進程
python的os模塊中的fork方法。來自於nuix/linux操作系統中提供的一個fork系統調用,這個方法非常特殊。普通的方法都是調用一次,返回一次,而fork方法是調用一次,返回兩次,原因在於操作系統將當前進程(父進程)複製出一份進程(子進程),這兩個進程幾乎完全相同,於是fork方法分別在父進程和子進程中返回。子進程中返回永遠是0,父進程中返回的是子進程的ID。示例:
os.getpid() 獲取當前進程的ID;
os.getppid() 獲取父進程的ID;
[root@jier ceshi]# cat ceshi.py
import os
if __name__ == '__main__':
print('current Process (%s) start ...'%(os.getpid()))
pid = os.fork()
if pid < 0:
print('error in fork')
elif pid == 0:
print('I an child process (%s) and my parent process is (%s)'%(os.getpid(), os.getppid()))
else:
print('I (%s) created a child process (%s)'%(os.getpid(), pid))
[root@jier ceshi]#
[root@jier ceshi]#
[root@jier ceshi]# python ceshi.py
current Process (18606) start ...
I (18606) created a child process (18639)
I an child process (18639) and my parent process is (18606)
[root@jier ceshi]#
2、使用 multiprocessing 模塊創建多進程
multiprocessing 模塊提供了一個Process 類來描述一個進程對象。創建子進程時,只需要傳入一個執行函數和函數對應的參數,即可完成一個Process 實例的創建,用start() 方法啓動進程,用join() 方法實現進程間的同步。示例:
[root@jier ceshi]# cat ceshi.py
import os
from multiprocessing import Process
def run_proc(name):
print('Child process %s (%s) Running...'%(name, os.getpid()))
if __name__ == '__main__':
print('Parent process %s.' %os.getpid())
for i in range(5):
p = Process(target = run_proc, args = (str(i),))
print('Process will start.')
p.start()
p.join()
print('Process end.')
[root@jier ceshi]# python ceshi.py
Parent process 19808.
Process will start.
Process will start.
Process will start.
Process will start.
Process will start.
Child process 0 (19841) Running...
Child process 3 (19844) Running...
Child process 2 (19843) Running...
Child process 4 (19845) Running...
Process end.
Child process 1 (19842) Running...
[root@jier ceshi]#
註釋:函數 run_proc 就是一個進程函數;
p = Process(target = run_proc, args = (str(i),)) 就是創建子進程的時候傳入的一個執行函數 run_proc 以及函數的參數 range(5);
用start()方法啓動進程;
用join()方法實現進程間的同步。