![](/img/trans.png)
[英]python multiprocessing on windows, if __name__ == “__main__”
[英]python3.x multiprocessing cycling without “if __name__ == '__main__':”
我有这个文件(它没有任何有用的工作,它只用于学习):
import multiprocessing,sys
def parent(numproc=2):
print ('at start')
childs=[]
print ('bfore Pipe')
(parentEnd,childEnd)=multiprocessing.Pipe()
i=0
print ('printing i:',i)
child=multiprocessing.Process(target=child_proc, args=(childEnd,i))
print ('created child')
child.start()
print ('started child')
print ('joining child')
child.join()
print ('joined child')
print ('exeted from for i in childs')
mins=[1,2]
print ('task ended. result: ',min(mins))
def child_proc(pipe,name):
pass
if __name__ == '__main__':
parent()
以这种形式运行完美:
at start
bfore Pipe
printing i: 0
created child
started child
joining child
joined child
exeted from for i in childs
task ended. result: 1
但如果我放入文件的末尾而不是
if __name__ == '__main__':
parent()
只要
parent()
它落在周期......
at start
bfore Pipe
printing i: 0
created child
started child
joining child
at start
bfore Pipe
printing i: 0
created child
started child
joining child
at start
bfore Pipe
printing i: 0
created child
started child
joining child
Traceback (most recent call last):
为什么?! 这个if条款有什么不同?
这是MS Windows上的multiprocessing
问题:主模块由子任务导入,因此任何代码都不受if __name__ . . .
保护if __name__ . . .
if __name__ . . .
子句再次运行,导致无限循环。
子进程具有以下__name__
: __parents_main__
而不是__main__
了。 这就是为什么在__name__
变量时,您的进程不会循环。
有关这方面的更多信息,请参阅安全导入主模块一章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.