concurrent.futures模块提供ThreadPoolExecutor和ProcessPoolExecutor两类执行器,分别用于I/O密集型和CPU密集型任务;通过submit提交任务返回Future对象,使用result获取结果,map实现并行映射,as_completed处理先完成的任务,配合with语句确保资源安全,适用于常见并发场景。

Python中的concurrent.futures模块提供了一种高级接口来异步执行可调用对象,使用线程或进程池非常方便。它通过ThreadPoolExecutor和ProcessPoolExecutor类简化了并发编程,适合处理I/O密集型或CPU密集型任务。
1. 基本概念与执行器类型
concurrent.futures的核心是Executor抽象类,有两个常用子类:
- ThreadPoolExecutor:适用于I/O密集型任务(如网络请求、文件读写)
- ProcessPoolExecutor:适用于CPU密集型任务(如数学计算、数据处理),能绕过GIL限制
两者都通过submit()提交任务,返回Future对象用于获取结果或状态。
2. 使用ThreadPoolExecutor
下面是一个多线程下载网页的例子:
立即学习“Python免费学习笔记(深入)”;
from concurrent.futures import ThreadPoolExecutor import requestsdef fetch_url(url): response = requests.get(url) return len(response.text)
urls = [ "https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c", "https://www.php.cn/link/ef246753a70fce661e16668898810624", "https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c" ]
with ThreadPoolExecutor(max_workers=3) as executor: futures = [executor.submit(fetch_url, url) for url in urls]
for future in futures: print(f"Result: {future.result()}")
说明:
- max_workers控制最大线程数
- submit()立即返回Future对象
- result()阻塞直到结果可用
3. 使用ProcessPoolExecutor
对于计算密集型任务,使用进程池更高效:
dmSOBC SHOP网店系统由北京时代胜腾信息技术有限公司(http://www.webzhan.com)历时6个月开发完成,本着简单实用的理念,商城在功能上摒弃了外在装饰的一些辅助功能,尽可能的精简各项模块开发,做到有用的才开发,网店V1.0.0版本开发完成后得到了很多用户的使用并获得了好评,公司立即对网店进行升级,其中包括修正客户提出的一些意见和建议,现对广大用户提供免费试用版本,如您在使用
from concurrent.futures import ProcessPoolExecutor import mathdef is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True
numbers = [1000003, 1000033, 1000037, 1000039]
with ProcessPoolExecutor() as executor: results = list(executor.map(is_prime, numbers))
print(results)
说明:
- map()类似内置map,但并行执行
- 函数必须可被pickle(不能是lambda或局部函数)
4. 处理多个任务的结果(as_completed)
如果希望任务一完成就处理结果,而不是按顺序等待,可以使用as_completed():
from concurrent.futures import ThreadPoolExecutor, as_completed import timedef task(n): time.sleep(n) return f"Task {n} done"
with ThreadPoolExecutor() as executor: futures = [executor.submit(task, t) for t in [3, 1, 2]]
for future in as_completed(futures): print(future.result())
输出会先显示耗时短的任务结果,实现“谁先完成谁先处理”。
基本上就这些。掌握submit、map、as_completed和Future.result()这几个核心方法,就能应对大多数并发场景。注意资源管理使用with语句,避免泄漏。不复杂但容易忽略细节。









