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()方法实现进程间的同步。