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 ThreadPoolExecutorimport 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
对于计算密集型任务,使用进程池更高效:
from concurrent.futures import ProcessPoolExecutorimport mathdef is_prime(n):if n < 2:return Falsefor i in range(2, int(math.sqrt(n)) + 1):if n % i == 0:return Falsereturn 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_completedimport 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语句,避免泄漏。不复杂但容易忽略细节。
以上就是Python中concurrent.futures模块如何使用的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1377839.html
微信扫一扫
支付宝扫一扫