python - 限制非守护程序池 Python 中的核心数
问题描述
我有一个脚本,我在其中运行一些带有 pool.apply_async 的进程并将它们作为非守护进程运行,以避免“僵尸”进程在内存方面的问题。到目前为止它运行良好,除了现在我已经扩展到内存中更大的数据集,所以通过使用我所有的内核,我正在明智地炸毁内存。我想限制在这些情况下使用的核心数量,但无法让它工作
通常我会集成如下内容
pool = Pool(self.nb_cores)
限制核心数量。但是我似乎无法找到将它集成到非守护进程中的位置。
import multiprocessing
import multiprocessing.pool
class NoDaemonProcess(multiprocessing.Process):
"""
Extends the multiprocessing Process class to disable
the daemonic property. Polling the daemonic property
will always return False and cannot be set.
"""
@property
def daemon(self):
"""
Always return False
"""
return False
@daemon.setter
def daemon(self, value):
"""
Pass over the property setter
:param bool value: Ignored setting
"""
pass
class NoDaemonContext(type(multiprocessing.get_context())):
"""
With the new multiprocessing module, everything is based
on contexts after the overhaul. This extends the base
context so that we set all Processes to NoDaemonProcesses
"""
Process = NoDaemonProcess
class NoDaemonPool(multiprocessing.pool.Pool):
"""
This extends the normal multiprocessing Pool class so that
all spawned child processes are non-daemonic, allowing them
to spawn their own children processes.
"""
def __init__(self, *args, **kwargs):
kwargs['context'] = NoDaemonContext()
super(NoDaemonPool, self).__init__(*args, **kwargs)
我知道我需要在某处集成一些核心限制......只是似乎无法在我的上下文中找到我需要的精确功能。
解决方案
您的自定义NoDaemonPool
类派生自multiprocessing.pool.Pool
因此将能够接受processes
(要使用的工作进程的数量)作为关键字参数:
pool = NoDaemonPool(processes=nb_cores)
推荐阅读
- netbeans - 任何有用的netbeans快捷方式?
- java - Java 类的 Clojure Ahead-of-Time 编译失败“找不到匹配的即时方法,为类 java.time.LocalDate 采用 2 个参数”
- r - dplyr 根据我们正在迭代的元素改变新列
- c# - IoT Hub 使用 Visual Studio Code 触发的 Azure Function App 问题
- ssl - Jetty 的机密端口和安全端口有什么区别
- java - Azure java SDK - 如何从事件中心读取事件?
- reactjs - 用 ref 重置输入字段的值?
- autodesk-forge - 如何使用 Autodesk.PDF 扩展从流中加载模型()
- android - 在描述 TapToFocus 的 CameraX 中的 Preview 中绘制圆
- c++ - C++20 概念:元素可迭代概念