2 回答

TA贡献2080条经验 获得超4个赞
如果您绝对必须使用 Python 多处理,那么您可以使用 Python 多处理和Arrow 的 Plasma 对象存储来将对象存储在共享内存中并从每个工作人员访问它。请参阅此示例,它使用 Pandas 数据帧而不是 numpy 数组执行相同的操作。
如果您不是绝对需要使用 Python 多处理,您可以使用Ray更轻松地做到这一点。Ray 的一个优点是它不仅可以处理数组,还可以处理包含数组的 Python 对象。
在幕后,Ray 使用Apache Arrow序列化 Python 对象,这是一种零拷贝数据布局,并将结果存储在Arrow 的 Plasma 对象存储中。这允许工作任务对对象进行只读访问,而无需创建自己的副本。您可以阅读有关其工作原理的更多信息。
这是您运行的示例的修改版本。
import numpy as np
import ray
ray.init()
@ray.remote
def worker_func(data, i):
# Do work. This function will have read-only access to
# the data array.
return 0
data = np.zeros(10**7)
# Store the large array in shared memory once so that it can be accessed
# by the worker tasks without creating copies.
data_id = ray.put(data)
# Run worker_func 10 times in parallel. This will not create any copies
# of the array. The tasks will run in separate processes.
result_ids = []
for i in range(10):
result_ids.append(worker_func.remote(data_id, i))
# Get the results.
results = ray.get(result_ids)
请注意,如果我们省略该行data_id = ray.put(data)而改为调用worker_func.remote(data, i),则data数组将在每次函数调用时存储在共享内存中,这将是低效的。通过第一次调用ray.put,我们可以将对象一次存储在对象存储中。
添加回答
举报