如何在 python 运行 中停止多重处理以获得完整脚本

How to stop multiprocessing in python running for the full script

我在python中有以下代码:

import multiprocessing
import time

print "I want this to show once at the beggining"

def leaveout():
    print "I dont Want This to Show"

def hang(input1):
        print "I want this to show 3 times"
        print "Number = %s" % input1

def main():
    p = multiprocessing.Process(target=hang, args=("0"))
    p.start()
    p1 = multiprocessing.Process(target=hang, args=("1"))
    p1.start()
    p2 = multiprocessing.Process(target=hang, args=("2"))
    p2.start()
    p.join()
    p1.join()
    p2.join()

if __name__ == '__main__':
    main()

print "I want this to show once at the end"

我的 objective 是在成功发生的三个实例中多处理挂起函数。我的问题是 main 函数还运行整个脚本的三个实例,结果如下:

c:\Evopt>python multiprocessingprac.py
I want this to show once at the beggining
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 2
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 1
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 0
I want this to show once at the end

我怎样才能阻止这种情况发生?

生成新进程时,Windows 创建一个空白进程。然后在生成的进程中加载​​一个新的 Python 解释器,并为它提供相同的代码库来解释。

这就是为什么您会看到重复执行打印语句的原因。由于它们是顶级表达式,因此每次进程评估该代码时都会执行它们。

在 Unix 操作系统中,这没有被观察到,因为它实现了一个完全不同的进程创建机制(fork 策略),不需要在子进程中再次加载新的 Python 解释器.

要解决您的问题,您需要从脚本中删除 print( ... ) 表达式并将它们移动到 main 函数中。

def main():
    print("I want this to show once at the beggining")

    p0 = multiprocessing.Process( ... )
    p0.start() 

    ...

    p2.join()

    print("I want this to show once at the end")

您可以在 multiprocessing documentation 中阅读有关流程启动策略的更多信息。