【发布时间】:2017-06-22 17:49:32
【问题描述】:
我希望concurrent.futures.ProcessPoolExecutor.map() 调用包含 2 个或更多参数的函数。在下面的示例中,我使用了lambda 函数并将ref 定义为与numberlist 大小相等且值相同的数组。
第一个问题:有更好的方法吗?在 numberlist 的大小可以是百万到十亿个元素的情况下,因此 ref 大小必须遵循 numberlist,这种方法不必要地占用宝贵的内存,我想避免这种情况。我这样做是因为我读到了map 函数将终止其映射,直到到达最短的数组末端。
import concurrent.futures as cf
nmax = 10
numberlist = range(nmax)
ref = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
workers = 3
def _findmatch(listnumber, ref):
print('def _findmatch(listnumber, ref):')
x=''
listnumber=str(listnumber)
ref = str(ref)
print('listnumber = {0} and ref = {1}'.format(listnumber, ref))
if ref in listnumber:
x = listnumber
print('x = {0}'.format(x))
return x
a = map(lambda x, y: _findmatch(x, y), numberlist, ref)
for n in a:
print(n)
if str(ref[0]) in n:
print('match')
with cf.ProcessPoolExecutor(max_workers=workers) as executor:
#for n in executor.map(_findmatch, numberlist):
for n in executor.map(lambda x, y: _findmatch(x, ref), numberlist, ref):
print(type(n))
print(n)
if str(ref[0]) in n:
print('match')
运行上面的代码,我发现map 函数能够达到我想要的结果。但是,当我将相同的条款转移到 concurrent.futures.ProcessPoolExecutor.map() 时,python3.5 失败并出现此错误:
Traceback (most recent call last):
File "/usr/lib/python3.5/multiprocessing/queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "/usr/lib/python3.5/multiprocessing/reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function <lambda> at 0x7fd2a14db0d0>: attribute lookup <lambda> on __main__ failed
问题 2:为什么会出现这个错误,如何让 concurrent.futures.ProcessPoolExecutor.map() 调用具有多个参数的函数?
【问题讨论】:
标签: python python-3.x lambda concurrency concurrent.futures