总览
一般的 Python 脚本只会用上单线程。对于 IO 密集型任务,用多线程加速会快得多。
本文会给出一个模板,使用 ThreadPoolExecutor
进行并行加速。
注意,由于 GIL 的存在,对于 CPU 密集型任务
ProcessPoolExecutor
是更好的选择。
快速使用 ThreadPoolExecutor
请看以下模板。
from concurrent.futures import ThreadPoolExecutor
def process_file(file):
with Image.open(file) as img:
···
return result
files = [···]
with ThreadPoolExecutor() as executor:
for result in executor.map(process_file, files):
···
process_file()
是需要多线程执行的函数files
装着若干process_file()
的输入。会以此生成若干个process_file()
任务executor.map()
返回一个迭代器
就这样,with ThreadPoolExecutor() as executor:
以内的代码会阻塞主线程,直到所有任务运行完毕。而 executor.map(process_file, files)
所生成的任务会并行运行,每次的运行结果会按顺序装入 result
,用于遍历结果。