【问题标题】:Multiprocessing shared variable not updating多处理共享变量不更新
【发布时间】:2017-06-18 12:21:24
【问题描述】:

在使用多处理模块时,我正在尝试更新共享变量(命名空间中的 numpy 数组)。但是,变量没有更新,我不明白为什么。

下面是一个示例代码来说明这一点:

from multiprocessing import Process, Manager
import numpy as np

chunk_size = 15
arr_length = 1000
jobs = []
namespace = Manager().Namespace()
namespace.arr = np.zeros(arr_length)
nb_chunk = arr_length/chunk_size + 1


def foo(i, ns):
    from_idx = chunk_size*i
    to_idx = min(arr_length, chunk_size*(i+1))
    ns.arr[from_idx:to_idx] = np.random.randint(0, 100, to_idx-from_idx)

for i in np.arange(nb_chunk):
    p = Process(target=foo, args=(i, namespace))
    p.start()
    jobs.append(p)
for i in np.arange(nb_chunk):
    jobs[i].join()

print namespace.arr[:10]

【问题讨论】:

    标签: python python-2.7 numpy multiprocessing python-multiprocessing


    【解决方案1】:

    您不能在 Python 中跨进程共享 listdict 等内置对象。为了在进程之间共享数据,Python's multiprocessing 提供了两种数据结构:

    另请阅读:Exchanging objects between processes

    【讨论】:

    【解决方案2】:

    问题在于Manager().Namespace() 对象没有注意到您正在使用ns.arr[from_idx:to_idx] = ... 更改任何内容(因为您正在处理内部数据结构),因此不会传播到其他进程。

    This answer 很好地解释了这里发生的事情。

    要修复它,请将列表创建为 Manager().List() 并将此列表传递给进程,以便 ns[from_idx:to_idx] = ... 被识别为更改并传播到进程:

    from multiprocessing import Process, Manager
    import numpy as np
    
    chunk_size = 15
    arr_length = 1000
    jobs = []
    arr = Manager().list([0] * arr_length)
    
    nb_chunk = arr_length/chunk_size + 1
    
    
    def foo(i, ns):
        from_idx = chunk_size*i
        to_idx = min(arr_length, chunk_size*(i+1))
        ns[from_idx:to_idx] = np.random.randint(0, 100, to_idx-from_idx)
    
    for i in np.arange(nb_chunk):
        p = Process(target=foo, args=(i, arr))
        p.start()
        jobs.append(p)
    for i in np.arange(nb_chunk):
        jobs[i].join()
    
    print arr[:10]
    

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2020-06-12
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多