如何向ThreadPool线程池传递列表与变量类型多参数?
线程池多参数传递实现方法
ThreadPool.map默认仅支持向目标函数传递单个可迭代对象拆分出的单元素参数,要同时传入列表、字符串等多类型参数,有两种可直接落地的实现方案:
方案1:用functools.partial固定公共参数(代码最简洁)
如果你的列表类型参数是所有任务共用的固定值,不需要随每个任务的id变化,直接用Python标准库的partial提前绑定固定参数,剩余的单个动态参数交给map传递即可。
from functools import partial from multiprocessing.pool import ThreadPool # 注意:不要用list作为变量名,会覆盖Python内置list类型,这里替换为实际业务变量名 def activate_item(common_param_list, object_id): # 编写你的业务逻辑 pass parallelism = 8 # 替换为你实际设置的并发数 thread_pool = ThreadPool(parallelism) your_fixed_list = [] # 替换为你需要传入的列表类型变量 with open('examples/1000_PSOrthoTile_ids.txt') as f: item_ids = f.read().splitlines()[:400] # 提前绑定固定的列表参数,生成的新函数仅需接收object_id单个参数 bind_fixed_param_func = partial(activate_item, your_fixed_list) thread_pool.map(bind_fixed_param_func, item_ids) thread_pool.close() thread_pool.join()
方案2:用starmap搭配参数元组列表(适配动态参数场景)
你之前查到的「所有传入参数封装为列表」的方案是starmap方法的标准用法,只要把固定参数和每个遍历得到的动态id组合成参数元组,就能直接适配你的场景,不需要复杂改造。这个方案适合列表参数也需要随任务动态变化的场景:
from multiprocessing.pool import ThreadPool def activate_item(common_param_list, object_id): # 编写你的业务逻辑 pass parallelism = 8 # 替换为你实际设置的并发数 thread_pool = ThreadPool(parallelism) your_fixed_list = [] # 替换为你需要传入的列表类型变量 with open('examples/1000_PSOrthoTile_ids.txt') as f: item_ids = f.read().splitlines()[:400] # 为每个任务组装完整的位置参数元组 task_params = [(your_fixed_list, item_id) for item_id in item_ids] # starmap会自动将每个元组拆分为独立的位置参数传入目标函数 thread_pool.starmap(activate_item, task_params) thread_pool.close() thread_pool.join()
补充说明:如果使用的是
concurrent.futures.ThreadPoolExecutor,除上述两种方案外,也可以在循环中调用submit方法逐个传入多参数,核心逻辑和上述方案一致。公共只读列表直接传引用即可,不会产生额外的内存拷贝开销。
内容的提问来源于stack exchange,提问作者Manap Shymyr
相关产品推荐
相关产品推荐

