concurrent.futures未按预期实现多线程,CPU密集型任务提速失败求助
问题原因与解决办法
两个核心问题导致多线程没生效
- 任务提交方式错误
你写的tpe.submit(burncpu())是直接在主线程里执行了burncpu函数,线程池根本没参与任务调度。正确的做法是把函数本身传给submit,不要加括号,这样线程池才会去调度执行这个函数:
tpe.submit(burncpu)
- 线程池不适合CPU密集型任务
Python有个全局解释器锁(GIL),同一时间只能有一个线程执行Python代码,所以ThreadPoolExecutor只能用来加速IO密集型任务(比如爬网页、读文件),对CPU密集型任务完全起不到并行加速的作用。
正确的解决方案:用多进程
针对CPU密集型任务,应该用 ProcessPoolExecutor,它会创建独立的进程,每个进程有自己的GIL,能真正把任务分配到多个CPU核心上并行执行。
修改后的完整代码:
import time, random from contextlib import contextmanager from multiprocessing import cpu_count import concurrent.futures as cf @contextmanager def timer(): start = time.time() yield end = time.time() print(f"This code block executed in {round(end - start, 3)} seconds.") def burncpu(): for i in range(100000): x = random.gauss(0, 1) # 单线程基准测试 with timer(): for _ in range(100): burncpu() print(f'I have {cpu_count()} cores available.') # 多进程并行测试 with timer(): with cf.ProcessPoolExecutor() as ppe: # 批量提交任务 futures = [ppe.submit(burncpu) for _ in range(100)] # 等待所有任务完成 cf.wait(futures)
运行这段代码后,你会看到执行时间比单线程版本大幅缩短,12个核心会被充分利用起来。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

