将字典传递给具有 python 中可修改元素的进程

Passing a dictionary to a Process with modifyable elements in python

我正在尝试使用多处理库的 Process 模块对我的代码进行线程处理以获得更好的性能。

代码的框架是为他们工作的每个线程创建字典,完成后,字典被汇总并保存到一个文件中。 资源创建如下:

histos = {}
for int i in range(number_of_threads):
    histos[i] = {}
    histos[i]['all'] =      ROOT.TH1F objects
    histos[i]['kinds_of'] = ROOT.TH1F objects
    histos[i]['keys'] =     ROOT.TH1F objects

然后在进程中,每个线程都使用自己的 histos[thread_number] 对象,处理包含的 ROOT.TH1F。 但是,我的问题是,显然如果我用这样的 Process 启动线程:

proc = {}
for i in range(Nthreads):
    it0 = 0 + i * n_entries / Nthreads  # just dividing up the workload
    it1 = 0 + (i+1) * n_entries / Nthreads 
    proc[i] = Process(target=RecoAndRecoFix, args=(i, it0, it1, ch,histos)) 
    # args: i is the thread id (index), it0 and it1 are indices for the workload,
    # ch is a variable that is read-only, and histos is what we defined before, 
    # and the contained TH1Fs are what the threads put their output into.
    # The RecoAndFix function works inside with histos[i], thus only accessing
    # the ROOT.TH1F objects that are unique to it. Each thread works with its own histos[i] object.
    proc[i].start()

那么线程确实可以访问它们的 histos[i] 对象,但不能写入它们。 准确地说,当我在 TH1F 直方图上调用 Fill() 时,没有填充任何数据,因为它无法写入对象,因为它们不是共享变量。

所以在这里:https://docs.python.org/3/library/multiprocessing.html 我发现我应该改为使用 multiprocessing.Array() 来创建一个可以由线程读取和写入的数组,如下所示:

typecoder = {}
histos = Array(typecoder,number_of_threads)
for int i in range(number_of_threads):
    histos[i] = {}
    histos[i]['all'] =      ROOT.TH1F objects
    histos[i]['kinds_of'] = ROOT.TH1F objects
    histos[i]['keys'] =     ROOT.TH1F objects

但是,它不接受字典作为类型。它不会工作,它说 TypeError: unhashable type: 'dict'

那么解决这个问题的最佳方法是什么? 我需要的是将存储在字典中的每个“各种键”的实例传递给每个线程,以便它们自己工作。而且他们必须能够编写这些接收到的资源。

感谢您的帮助,如果我忽略了一些琐碎的事情,我深表歉意,我以前做过线程代码,但还没有 python。

缺少的部分是“进程”和“线程”之间的区别;您将它们混合在 post 中,但您的方法仅适用于线程,不适用于进程。

线程都共享内存;他们都将引用同一个字典,因此可以使用它来相互通信以及与 parent.

进程有独立的内存;每个人都会得到自己的字典副本。如果他们想沟通,他们必须通过其他方式进行沟通(例如,使用 multiprocessing.Queue)。另一方面,这意味着他们得到了分离的安全。

Python 中的另一个并发症是“GIL”;线程将大部分串行共享相同的 Python 解释器,只有 运行 在执行 I/O 时并行,访问网络或一些为其提供特殊规定的库(numpy,图像处理,其他几个)。同时,进程获得完全并行性。

Python 多处理模块有一个管理器 class,它提供可以跨线程和进程共享的字典。

有关示例,请参阅文档:https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes