天天看点

Python - multiprocessing运行和停止进程

基本用法

本文介绍控制进程启停的操作, 只用到一个

Process

首先写一个保持运行的方法:

def run_forever():
    while 1:
        print(time.time())
        time.sleep(2)
           

初始化一个

Process

实例, target为该实例运行时执行的方法.

通过调用

Process

类的

start

方法启动一个进程:

from multiprocessing import Process

p = Process(target=run_forever)
p.start()
           

要停止一个进程实例,可以调用方法

terminate

:

p.terminate()
           

但是通过执行系统命令

ps

查看停止后的进程, 你会发现, 直接调用

terminate

方法停止的进程变成了一个僵尸进程(defunct), 只能等待主程序退出, 这个僵尸进程才会消失.

通过在

terminate

后添加一次调用

join

方法等待进程真正结束, 就能避免出现僵尸进程:

p.join()
           

完整代码

import time
from multiprocessing import Process


def run_forever():
    while 1:
        print(time.time())
        time.sleep(2)


def main():
    p = Process(target=run_forever)
    p.start()
    print('start a process.')
    time.sleep(10)
    if p.is_alive:
        # stop a process gracefully
        p.terminate()
        print('stop process')
        p.join()


if __name__ == '__main__':
    main()
           

参考

[1] multiprocessing, Python

[2] python multiprocessing: why is process defunct after terminate?, Stack Overflow