这段时间的工作中频繁使用线程池,而任务函数需要传递多个参数; 在之前的认知中,线程池都只能传递一个参数,参数可以是列表、元组、生成器。这个问题困扰了我很久,今天偶然间看到一位佬的文章,学习到了一种传递多个参数的方法。
以往的线程池并行任务用法
from concurrent.futures import ThreadPoolExecutor
def my_func(arg):
args1, args2, args3 = arg
""" 任务逻辑省略 """
print(args1, args2, args3)
return
tasks = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
with ThreadPoolExecutor(2) as pool:
result = pool.map(my_func, tasks)
这种用法只能传递一个参数,如果任务函数有多个参数时就会报错。
用lambda匿名函数的方式进行多个参数的传递
from concurrent.futures import ThreadPoolExecutor
def my_function(arg1, arg2):
# do something with arg1 and arg2
print(arg1 + arg2)
tasks = [(1, 5), (2, 6), (3, 7), (4, 8)]
executor = ThreadPoolExecutor(max_workers=len(tasks))
results = executor.map(lambda x: my_function(*x), tasks)
这个代码中,任务列表中的每一个元组表示一个任务函数的实参元组,正常直接进行传递是无法传递给任务函数的,所以这里通过lambda函数对元组进行解包,这样就可以把多个参数传递到任务函数了。