Zexian Li

Python多进程

2020-05-11 · 2 min read

Unix/Linux下可通过fork()调用实现多进程。对于Python,在Unix/Linux下,其multiprocessing模块封装了fork()的调用,在Windows中,multiprocessing通过将父进程的所有Python对象通过pickle序列化并传到子进程中来模拟fork()的效果。

###一段最基本的多进程代码

from multiprocessing import Process
import os

def run_proc(name):
    print('Run child process {} and the pid is {}.'.format(name, os.getpid()))

if __name__=='__main__':
    print('Parent process {}.'.format(os.getpid()))
    p = Process(target=run_proc, args=('test',))
    print('Child process will start.')
    p.start()   # start a child process.
    p.join()    # wait for the end of child process.
    print('Child process end.')

此时的输出如下所示:

Parent process 66596.
Child process will start.
Run child process test and the pid is 66599.
Child process end.

创建子进程,就是向Process实例传入一个执行函数和该函数的参数,使用start()方法启动该执行函数。
注意,当注释掉p.join()语句时,主进程不会等待子进程结束,对应的输出也会发生如下的改变:

Parent process 66616.
Child process will start.
Child process end.
Run child process test and the pid is 66618.
Bad decisions make good stories.