我在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"
我的目标是在三个实例中多处理挂起函数,这正在成功发生。我的问题是 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")
您可以在多处理文档中阅读有关进程启动策略的更多信息。