ThreapPool.map出现不支持的操作数类型异常,但map却没有?

1 投票
1 回答
798 浏览
提问于 2025-04-16 08:41

为什么内置的map函数可以用,而多线程的ThreadPool的map函数却不行呢?

from multiprocessing.pool import ThreadPool

def identity(a, b): return (a, b)

map(identity, [1, 2, 3], [4, 5, 6])

p = ThreadPool(2)

#gives above error:
p.map(identity, [1, 2, 3], [4, 5, 6])

补充说明:经过一些调查,发现ThreadPool的map函数不支持那种可以接受多个参数的写法,也就是说,它不能像map(f, i1, i2, i3,...in)这样使用,其中i1是f的第一个参数,i2是第二个参数,依此类推。出现异常是因为我给它的列表被当作了块大小或其他某个整数参数来处理。

无论如何,能提供一些好的解决方案就太好了。

1 个回答

1
from multiprocessing.pool import ThreadPool

def identity((a,b)): return a, b

print map(identity, zip([1, 2, 3], [4, 5, 6]))

p = ThreadPool(2)

#gives above error:
print p.map(identity, zip([1, 2, 3], [4, 5, 6]))
[(1, 4), (2, 5), (3, 6)]
[(1, 4), (2, 5), (3, 6)]

输出

撰写回答