掘金 后端 ( ) • 2022-01-26 15:41

「这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战

multiprocessing模块提供了一个Process类来代表一个进程对象。在multiprocessing中,每一个进程都用一个Process类来表示。

1.基本介绍

1.1 构造方法

Process(group=None, target=None, name=None, args=(), kwargs={},
             *, daemon=None)

group:分组,实际上不使用,值始终为None

target:表示调用对象,即子进程要执行的任务,支持方法名

name:为子进程设定名称

args:要传递给target函数的位置参数,以元组的形式进程传递

kwargs:要传给target函数的字典参数,以字典的形式进行传递

daemon:是否进程进程守护,True代表开启进程守护,False代表关闭进程守护

1.2 实例方法

start():启动进程,并调用该子进程中的run()方法

run():进程启动时运行的方法。

terminate():强制终止进程,不会进行任何清理操作。若被终止的进程创建了子进程,那么该子进程就成为了僵尸进程。若被终止的进程保存了有个锁也不会被释放,进而导致死锁。

is_alive():进程是否在运行在运行返回True,否则为False

join([timeout]):进程同步,主进程等待子进程完成后再执行后面的代码超过timeout设定的时间,主进程将不再等待。这里要注意,该方法只对start()启动的进程有效,对于run()开启的进程没什么用。

1.3 属性

daemon:默认值为False。如果值为True,代表被操作的进程为后台运行的守护进程,且该进程无法创建新的进程。当该进程的父进程终止后,该进程也随之终止。daemon属性要在start()之前进行设置

name:进程的名称

pid:进程的pid

2.使用实例

from multiprocessing import Process
import os
​
​
def run_process(name):
    print(f"Run child process {name} ({os.getpid()})")
​
​
if __name__ == '__main__':
    print(f"Parent process {os.getpid()}")
    p = Process(target=run_process, args=("第一个进程",))
    print("child process start")
    p.start()
    p.join()
    print("child process end")

result:

Parent process 11020
child process start
Run child process 第一个进程 (14792)
child process end

在Windows下Process()必须放在if $$name$$ == '$$main$$':中,否则会报错

RuntimeError: 
    An attempt has been made to start a new process before the current process has finished its                 bootstrapping phase.This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:
​
    if __name__ == '__main__':
    freeze_support()
    ...
​
    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.