模块介绍concurrent.futures 模块是 Python 3 中用于并发编程的标准库之一。它提供了一个高级接口来异步执行可调用对象。这些接口让线程和进程池管理变得非常简便,且适用于多种并发编程需求。
此模块主要包含两个执行模块:
ThreadPoolExecutor:用于管理线程池,适用于 I/O 绑定的任务。 ProcessPoolExecutor:用于管理进程池,适用于 CPU 绑定的任务。 此模块适用于 Python 3.2 及以上版本。
应用场景concurrent.futures 模块主要用于简化异步编程中的线程和进程管理。它提供了统一的接口来管理多线程和多进程任务,适合同步或异步地执行任务。常见的应用场景包括:
I/O 密集型任务(如文件操作、网络请求) CPU 密集型任务(如数据处理、计算密集型任务) 并行处理多个独立任务,提高程序效率 安装说明concurrent.futures 是 Python 3 的默认库,无需额外安装。只需要在代码中导入即可:
1 import concurrent.futures
用法举例 1. 使用 ThreadPoolExecutor 进行多线程操作场景:从多个 URL 并行下载网页内容,以提高下载效率。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import concurrent.futures import requests urls = [ 'http://www.example.com' , 'http://www.example.org' , 'http://www.example.net' ] def fetch_url (url ): """下载指定URL的内容""" response = requests.get(url) return response.text with concurrent.futures.ThreadPoolExecutor(max_workers=3 ) as executor: futures = {executor.submit(fetch_url, url): url for url in urls} for future in concurrent.futures.as_completed(futures): url = futures[future] try : data = future.result() print (f"{url} downloaded successfully" ) except Exception as e: print (f"{url} generated an exception: {e} " )
2. 使用 ProcessPoolExecutor 进行多进程操作场景:并行计算一组数字的阶乘值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import concurrent.futures import math numbers = [5 , 10 , 20 , 30 ] def factorial (n ): """计算n的阶乘""" return math.factorial(n) with concurrent.futures.ProcessPoolExecutor(max_workers=4 ) as executor: results = list (executor.map (factorial, numbers)) for number, result in zip (numbers, results): print (f"Factorial of {number} is {result} " )
3. 使用 as_completed 进行任务完成的异步回调处理场景:并行处理一组任务并在任务完成后立即处理其结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import concurrent.futures import time def task (n ): """模拟任务处理""" time.sleep(n) return f"Task {n} completed" tasks = [2 , 3 , 1 , 4 ] with concurrent.futures.ThreadPoolExecutor(max_workers=4 ) as executor: futures = {executor.submit(task, task): task for task in tasks} for future in concurrent.futures.as_completed(futures): task = futures[future] try : result = future.result() print (result) except Exception as e: print (f"Task {task} generated an exception: {e} " )
通过上述示例,可以看到 concurrent.futures 模块提供了一种简洁的方式来处理并发任务,无论是多线程还是多进程,都能方便地管理和获取任务结果。
强烈建议大家关注我的博客 —— 全糖冲击博客。这里不仅包含了所有 Python 标准库的使用教程,还提供了详细的代码示例和深入的技术讲解,帮助你快速掌握 Python 编程。如果你在编程学习过程中遇到了问题,也可以在博客留言,我会及时回复并提供帮助。关注全糖冲击博客,让编程学习更加高效和有趣!
软件版本可能变动
如果本文档不再适用或有误,请留言或联系我进行更新。让我们一起营造良好的学习氛围。感谢您的支持! - Travis Tang