python - 为什么这个多处理代码会失败?

标签 python

<分区>

def sample():
    pass

Process(target=sample).start()
Process(target=sample).start()

上述代码因错误而失败:

An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module

但是这段代码运行良好:

def sample():
    pass
if __name__ == '__main__':
    Process(target=sample).start()
    Process(target=sample).start()

为什么在这种情况下主模块会影响我的代码执行?我无法正确理解错误消息。

注意:我经历了What does if __name__ == "__main__": do?但无法理解它与我的代码的相关性。

最佳答案

当您创建新的子进程时,子进程可能(主要取决于您使用的操作系统)重新导入当前模块。

在您的情况下,重新导入模块也会执行这两行:

Process(target=sample).start()
Process(target=sample).start()

发生的事情是,错误消息告诉您:

An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module

在为您的第一个子进程设置适当的环境时,代码会尝试派生出另一个子进程。经理检测到这一点并告诉您这不行。

if __name__ == '__main__':
    Process(target=sample).start()
    Process(target=sample).start()

是一个保护条件,它允许当前模块导入子模块而不会出现这个问题,因为只有 --well-- 主模块的名称是 __main__ .

关于python - 为什么这个多处理代码会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34223502/

相关文章:

python用语言环境设置自己的货币

python - Python 中的最大素数回文

python - 在 python 中更新访问 token

Debian Lenny 上的 Python 2.6。可执行文件应该去哪里?

python - 类型错误 : no salt specified in flask(about sha256)

python - 从三个一维数组创建热图

python - 使用用户输入查找列表中的元素

python - URL错误 : <urlopen error [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl. c:661)>

python - 随机词生成器 - Python

python - 为什么追加或连接后 Pandas 数据框的大小不同?