我需要将 5 个参数传递给 multiprocessing.pool.map。我可以使用 itertools.partial 成功通过 2,但我需要更多这样我可以使用计数器,使用计数器需要锁和共享计数器。我看了堆栈上的另一个问题,但它不适用于我目前的情况。
这是我目前使用部分的代码:
import multiprocessing
from multiprocessing import Pool, Value, Lock
from itertools import partial
def check(argumentnumberone, iteratorr):
#MY CODE HERE
def main():
pool = Pool(numbofthreadshere)
pool.daemon = True
func2 = partial(check, goodones)#this is argumentone
result = pool.map(func2, arrange)#this is the iterator
我需要传递一个锁、计数器和至少 1 个参数来检查((,我将如何做到这一点,我当前的代码工作正常,没有错误。
你想要做的是准备参数列表并将元组或参数列表传递给池映射,而不是使用部分:
def check(*args):
print('check', args)
def main():
pool = Pool(8)
pool.daemon = True
result = pool.map(check, [(1, 2, 3), (4, 5, 6)])
main()
或者你可以像这样使用部分:
import multiprocessing
from multiprocessing import Pool, Value, Lock
from functools import partial
def check(*args):
print('check', args)
def main():
pool = Pool(8)
pool.daemon = True
my_func = partial(check, 'arg0 from partial', 'arg1 from partial')
result = pool.map(my_func, range(10))
main()
最后一个代码段将输出以下内容:
check ('arg0 from partial', 'arg1 from partial', 0)
check ('arg0 from partial', 'arg1 from partial', 1)
check ('arg0 from partial', 'arg1 from partial', 2)
check ('arg0 from partial', 'arg1 from partial', 3)
check ('arg0 from partial', 'arg1 from partial', 4)
check ('arg0 from partial', 'arg1 from partial', 5)
check ('arg0 from partial', 'arg1 from partial', 8)
check ('arg0 from partial', 'arg1 from partial', 6)
check ('arg0 from partial', 'arg1 from partial', 9)
check ('arg0 from partial', 'arg1 from partial', 7)