登录
首页 >  文章 >  python教程

Python并发编程实战指南

时间:2025-11-11 13:36:45 334浏览 收藏

文章不知道大家是否熟悉?今天我将给大家介绍《Python并发模块使用教程》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

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

Python中concurrent.futures模块如何使用

Python中的concurrent.futures模块提供了一种高级接口来异步执行可调用对象,使用线程或进程池非常方便。它通过ThreadPoolExecutorProcessPoolExecutor类简化了并发编程,适合处理I/O密集型或CPU密集型任务。

1. 基本概念与执行器类型

concurrent.futures的核心是Executor抽象类,有两个常用子类:

  • ThreadPoolExecutor:适用于I/O密集型任务(如网络请求、文件读写)
  • ProcessPoolExecutor:适用于CPU密集型任务(如数学计算、数据处理),能绕过GIL限制

两者都通过submit()提交任务,返回Future对象用于获取结果或状态。

2. 使用ThreadPoolExecutor

下面是一个多线程下载网页的例子:

from concurrent.futures import ThreadPoolExecutor
import requests
<p>def fetch_url(url):
response = requests.get(url)
return len(response.text)</p><p>urls = [
"<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpV6iZXHe3vUmsyZr5vTk6a8eYanvpGjpn2MhqKu3LOijnmMlbN4cpSSt89pkqp5qLBkep6yo6Nkf42hpLLdyqKBrIXRsot-lpHdz3Y' rel='nofollow'>https://httpbin.org/delay/1</a>",
"<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpV6iZXHe3vUmsyZr5vTk6a8eYanvpGjpn2ihqKu3LOijnmMlbN4cpSSt89pkqp5qLBkep6yo6Nkf42hpLLdyqKBrIXRsot-lpHdz3Y' rel='nofollow'>https://httpbin.org/delay/2</a>",
"<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpV6iZXHe3vUmsyZr5vTk6a8eYanvpGjpn2MhqKu3LOijnmMlbN4cpSSt89pkqp5qLBkep6yo6Nkf42hpLLdyqKBrIXRsot-lpHdz3Y' rel='nofollow'>https://httpbin.org/delay/1</a>"
]</p><p>with ThreadPoolExecutor(max_workers=3) as executor:
futures = [executor.submit(fetch_url, url) for url in urls]</p><pre class="brush:python;toolbar:false;">for future in futures:
    print(f"Result: {future.result()}")

说明:
- max_workers控制最大线程数
- submit()立即返回Future对象
- result()阻塞直到结果可用

3. 使用ProcessPoolExecutor

对于计算密集型任务,使用进程池更高效:

from concurrent.futures import ProcessPoolExecutor
import math
<p>def 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</p><p>numbers = [1000003, 1000033, 1000037, 1000039]</p><p>with ProcessPoolExecutor() as executor:
results = list(executor.map(is_prime, numbers))</p><p>print(results)</p>

说明:
- map()类似内置map,但并行执行
- 函数必须可被pickle(不能是lambda或局部函数)

4. 处理多个任务的结果(as_completed)

如果希望任务一完成就处理结果,而不是按顺序等待,可以使用as_completed()

from concurrent.futures import ThreadPoolExecutor, as_completed
import time
<p>def task(n):
time.sleep(n)
return f"Task {n} done"</p><p>with ThreadPoolExecutor() as executor:
futures = [executor.submit(task, t) for t in [3, 1, 2]]</p><pre class="brush:python;toolbar:false;">for future in as_completed(futures):
    print(future.result())

输出会先显示耗时短的任务结果,实现“谁先完成谁先处理”。

基本上就这些。掌握submitmapas_completedFuture.result()这几个核心方法,就能应对大多数并发场景。注意资源管理使用with语句,避免泄漏。不复杂但容易忽略细节。

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>