简体   繁体   English

尝试使用多重处理在python中填充数组

[英]Trying to use multiprocessing to fill an array in python

I have a code like this 我有这样的代码

x = 3;
y = 3;
z = 10;
ar = np.zeros((x,y,z))

from multiprocessing import Process, Pool

para = []
process = []
def local_func(section):
    print "section %s" % str(section)
    ar[2,2,section] = 255
    print "value set %d", ar[2,2,section]

pool = Pool(1)

run_list = range(0,10)
list_of_results = pool.map(local_func, run_list)

print ar

The value in ar was not changed with multithreading, what might be wrong? ar中的值未通过多线程更改,这可能是什么问题?

thanks 谢谢

You're using multiple processes here, not multiple threads. 您在这里使用多个进程,而不是多个线程。 Because of that, each instance of local_func gets its own separate copy of ar . 因此, local_func每个实例local_func获得其自己的ar单独副本。 You can use a custom Manager to create a shared numpy array, which you can pass to each child process and get the results you expect: 您可以使用自定义Manager来创建共享的numpy数组,您可以将其传递给每个子进程并获得所需的结果:

import numpy as np
from functools import partial
from multiprocessing import Process, Pool
import multiprocessing.managers

x = 3;
y = 3;
z = 10; 

class MyManager(multiprocessing.managers.BaseManager):
    pass
MyManager.register('np_zeros', np.zeros, multiprocessing.managers.ArrayProxy)


para = []
process = []
def local_func(ar, section):
    print "section %s" % str(section)
    ar[2,2,section] = 255 
    print "value set %d", ar[2,2,section]

if __name__ == "__main__":
    m = MyManager()
    m.start()
    ar = m.np_zeros((x,y,z))

    pool = Pool(1)

    run_list = range(0,10)
    func = partial(local_func, ar)
    list_of_results = pool.map(func, run_list)

    print ar

Well, multi-threading and multi-processing are different things. 好吧,多线程和多处理是不同的事情。

With multi-threading threads share access to the same array. 使用多线程线程共享对同一阵列的访问。

With multi-processing each process has its own copy of the array. 通过多处理,每个进程都有自己的数组副本。

multiprocessing.Pool is a process pool, not a thread pool. multiprocessing.Pool是一个进程池,而不是线程池。

If you want thread pool, use multiprocess.pool.ThreadPool : 如果需要线程池,请使用multiprocess.pool.ThreadPool


Replace: 更换:

from multiprocessing import Pool

with: 与:

from multiprocessing.pool import ThreadPool as Pool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM