没有 "if __name__ == ' __main_ _':"的 python3.x 多处理循环

标签 python python-3.x multiprocessing

我有这个文件(它没有做任何有用的工作,仅供学习):

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__ == ' __main_ _':"的 python3.x 多处理循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501048/

相关文章:

c++ - 从另一个应用程序在 Cygwin 中运行 bash 命令

python - 如何使用 python 过滤 CSV 文件中两个日期之间的行并重定向到另一个文件?

Python 多处理 : calling methods and passing objects in asynchronous calls

python - pyside:QFileDialog 返回一个空列表

python - 在 AWS 上使用 Spotipy 通过 Python 对 Spotify 进行用户身份验证

Python 递归,为什么我的函数不起作用?

python - 如何在 PyQt5 窗口中嵌入 pptk 查看器

bash - 如何编写进程池 bash shell

Python多处理 - 进程完成后如何释放内存?

python - linux中如何控制后台进程