如何用ThreadPoolExecutor将两个列表的所有组合传入多线程函数
如何用ThreadPoolExecutor实现两个列表元素的全组合多线程调用?
嘿,我来帮你搞定这个问题!你需要的是把两个列表的所有元素组合(也就是笛卡尔积)作为参数传给test函数,用ThreadPoolExecutor来并行执行。这里有个完整的可运行实现方案:
首先,我们需要导入必要的模块,然后生成两个列表的所有元素组合,再提交给线程池处理:
from concurrent.futures import ThreadPoolExecutor, as_completed import itertools def test(hello, world): return hello + world if __name__ == "__main__": a = [1, 2, 3, 4] b = [9, 8, 7, 6] # 生成两个列表的所有元素组合(笛卡尔积) all_combinations = itertools.product(a, b) with ThreadPoolExecutor(max_workers=10) as executor: # 提交所有任务,用字典关联future和对应的参数对 future_to_stuff = { executor.submit(test, hello, world): (hello, world) for hello, world in all_combinations } # 按任务完成顺序处理结果 for future in as_completed(future_to_stuff): hello, world = future_to_stuff[future] try: result = future.result() print(f"test({hello}, {world}) 返回结果: {result}") except Exception as exc: print(f"test({hello}, {world}) 执行出错: {exc}")
关键点解释:
itertools.product(a, b):这个工具会帮你生成两个列表所有可能的元素配对,比如(1,9)、(1,8)、(2,9)……省去了手动写嵌套循环的麻烦,代码更简洁高效。future_to_stuff字典:把每个提交任务返回的Future对象和对应的参数对绑定,这样当任务完成时,你能明确知道当前结果对应的是哪一组输入参数,方便后续的结果跟踪和日志输出。as_completed(future_to_stuff):这个函数会按任务实际完成的顺序返回Future对象,而不是按你提交任务的顺序,这样能让你更快拿到已经完成的任务结果,提升处理效率。
内容的提问来源于stack exchange,提问作者Jimmy Sanchez
相关产品推荐
相关产品推荐

