防止多处理"失控的错误"

max*_*max 5 python linux windows process multiprocessing

如果您使用多处理并且意外地最终创建无限制的进程,操作系统将不会喜欢它.

是否有任何简单的解决方案可以防止这种情况发生(例如,通过限制Python或OS中的进程总数)?

我使用Windows,当我犯这样的错误时,它的表现非常糟糕(需要硬重启).所以我喜欢它,如果有一些代码可以包含/添加到我的应用程序并防止这种情况发生.

Eth*_*man 3

您可以做的是创建一个短的“绊线”类型模块并将其导入以及多重处理。如果 Trip-wire 模块检测到多处理无限循环,它将引发异常。

我的看起来像这样:

#mp_guard.py
"""tracks invocation by creating an environment variable; if that
variable exists when next called a loop is in progress"""

import os

class Brick(Exception):
    def __init__(self):
        Exception.__init__(self, "Your machine just narrowly avoided becoming"
                                 " a brick!")

if 'MP_GUARD' in os.environ:
    raise Brick

os.environ['MP_GUARD'] = 'active'
Run Code Online (Sandbox Code Playgroud)

在主 .py 文件中:

import mp_guard
Run Code Online (Sandbox Code Playgroud)