gpt4 book ai didi

python - 为什么这个 multiprocessing.pool 的实现不起作用?

转载 作者:太空狗 更新时间:2023-10-30 00:55:47 25 4
gpt4 key购买 nike

这是我使用的代码:

def initFunction(arg1, arg2):
def funct(value):
return arg1 * arg2 * value
return funct

os.system("taskset -p 0xff %d" % os.getpid())
pool = Pool(processes=4)
t = np.linspace(0,1,10e3)

a,b,c,d,e,f,g,h = sy.symbols('a,b,c,d,e,f,g,h',commutative=False)

arg1 = sy.Matrix([[a,b],[c,d]])
arg2 = sy.Matrix([[e,f],[g,h]])
myFunct = initFunction(arg1, arg2)

m3 = map(myFunct,t) # this works
m4 = pool.map(myFunct,t) # this does NOT work

我得到的错误是:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/justin/Research/mapTest.py", line 46, in <module>
m4 = pool.map(myFunct,t)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 558, in get
raise self._value
cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

那么这个错误是什么意思,我该如何多处理这个 map 函数?

最佳答案

使用多处理时在进程之间传递的对象必须可从__main__模块导入,so that they can be unpickled在 child 身上。嵌套函数,如 funct,不能从 __main__ 导入,所以你会得到那个错误。您可以使用 functools.partial 来实现您正在尝试的目标相反:

from multiprocessing import Pool
from functools import partial

def funct(arg1, arg2, value):
return arg1 * arg2 * value


if __name__ == "__main__":
t = [1,2,3,4]
arg1 = 4
arg2 = 5

pool = Pool(processes=4)
func = partial(funct, arg1, arg2)
m4 = pool.map(func,t)
print(m4)

输出:

[20, 40, 60, 80]

关于python - 为什么这个 multiprocessing.pool 的实现不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com