首页 > 解决方案 > 共享对象中的python多进程和线程安全

问题描述

我对线程安全和多处理有点不确定。

据我所知, multiprocessing.Pool.map 腌制调用函数或对象,但保持引用传递的成员完好无损。

这似乎是有益的,因为它可以节省内存,但我没有在这些对象中找到任何有关线程安全的信息。

就我而言,我正在尝试从磁盘读取 numpy 数据,但是,我希望能够在不更改实现的情况下修改源代码,因此我将读取部分分解为自己的类。

我大致有以下情况:


import numpy as np
from multiprocessing import Pool

class NpReader():
    def read_row(self, row_index):
        pass

class NpReaderSingleFile(NpReader):
    def read_row(self, row_index):
        return np.load(self._filename_from_row(row_index))

    def _filename_from_row(self, row_index):
        return Path(row_index).with_suffix('.npy')

class NpReaderBatch(NpReader):
    def __init__(self, batch_file, mmap_mode=None):
        self.batch = np.load(batch_file, mmap_mode=mmap_mode)

    def read_row(self, row_index):
        read_index = row_index
        return self.batch[read_index]

class ProcessRow():
    def __init__(self, reader):
        self.reader = reader

     def __call__(self, row_index):
         return reader.read_row(row_index).shape

readers = [
    NpReaderSingleFile(),
    NpReaderBatch('batch.npy'),
    NpReaderBatch('batch.npy', mmap_mode='r')
]

res = []
for reader in readers:
    with Pool(12) as mp:
        res.append(mp.map(ProcessRow(reader), range(100000))

在我看来,这里有很多可能出错的地方,但不幸的是,我没有知识来确定测试它的内容。

上述方法有什么明显的问题吗?

我想到的一些事情是:

  1. np.load (它似乎适用于小型单个文件,但我可以对其进行测试以查看它是否安全?
  2. NpReaderBatch 是安全的还是 read_index 可以被不同的进程同时修改?

标签: pythonpython-3.xnumpypython-multiprocessing

解决方案


推荐阅读