嗨,我试图用多,以加快我的代码。但是,apply_async不适用于我。我试图做一个简单的例子,如:的Python - apply_async不执行功能
from multiprocessing.pool import Pool
t = [0, 1, 2, 3, 4, 5]
def cube(x):
t[x] = x**3
pool = Pool(processes=4)
for i in range(6):
pool.apply_async(cube, args=(i,))
for x in t:
print(x)
它并没有真正改变t如我所料。
我真正的代码如下:
from multiprocessing.pool import Pool
def func(a, b, c, d):
#some calculations
#save result to files
#no return value
lt = #list of possible value of a
#set values to b, c, d
p = Pool()
for i in lt:
p.apply_async(func, args=(i, b, c, d,))
哪里是这里的问题?
谢谢!
更新:感谢评论和答案,现在我明白了为什么我的简单示例不起作用。但是,我仍然遇到了我的真实代码问题。我已经检查过我的func不依赖任何全局变量,所以它看起来不像我的示例代码那样。
至于建议,我添加了一个返回值,我func,现在我的代码是:
f = Flux("reactor")
d = Detector("Ge")
mv = arange(-6, 1.5, 0.5)
p = Pool()
lt = ["uee", "dee"]
for i in lt:
re = p.apply_async(res, args=(i, d, f, mv,))
print(re.get())
p.close()
p.join()
现在我得到以下错误:
Traceback (most recent call last):
File "/Users/Shu/Documents/Programming/Python/Research/debug.py", line 35, in
print(re.get())
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 608, in get
raise self._value
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 385, in _handle_tasks
put(task)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'Flux.__init__..'
2017-07-04
Shu Liao
+0
是'FUNC()'不创建文件不如预期,或者你只是没有看到任何速度优势? –
+0
@JohnGordon'func'不会做任何事情,就像我的第一个例子'cube'没有执行。 –
+0
您假定每个进程共享相同的全局't',这是从定义上来说是不可信的。您必须将't'作为参数传递,以便't'存在并且被所有进程共享。 –