推荐答案
// www.javascriptcn.com code example
import concurrent.futures
import time
# 定义一个简单的任务函数
def task(n):
time.sleep(n)
return f"Task {n} completed"
# 使用线程池
def use_thread_pool():
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
# 提交任务到线程池
futures = [executor.submit(task, n) for n in range(1, 4)]
# 获取任务结果
for future in concurrent.futures.as_completed(futures):
print(future.result())
# 使用进程池
def use_process_pool():
with concurrent.futures.ProcessPoolExecutor() as executor:
# 提交任务到进程池
futures = [executor.submit(task, n) for n in range(1, 4)]
# 获取任务结果
for future in concurrent.futures.as_completed(futures):
print(future.result())
if __name__ == "__main__":
print("Using Thread Pool:")
use_thread_pool()
print("\nUsing Process Pool:")
use_process_pool()本题详细解读
1. concurrent.futures 模块简介
concurrent.futures 是 Python 标准库中的一个模块,提供了高级接口来异步执行可调用对象。它主要包含两个类:ThreadPoolExecutor 和 ProcessPoolExecutor,分别用于线程池和进程池的操作。
2. ThreadPoolExecutor 线程池
- 作用:
ThreadPoolExecutor用于创建线程池,适合 I/O 密集型任务。 - 使用方法:
- 使用
with语句创建ThreadPoolExecutor实例,并指定最大线程数max_workers。 - 使用
executor.submit()方法提交任务到线程池,返回一个Future对象。 - 使用
concurrent.futures.as_completed()方法获取已完成的任务结果。
- 使用
3. ProcessPoolExecutor 进程池
- 作用:
ProcessPoolExecutor用于创建进程池,适合 CPU 密集型任务。 - 使用方法:
- 使用
with语句创建ProcessPoolExecutor实例。 - 使用
executor.submit()方法提交任务到进程池,返回一个Future对象。 - 使用
concurrent.futures.as_completed()方法获取已完成的任务结果。
- 使用
4. Future 对象
- 作用:
Future对象表示异步计算的结果。 - 常用方法:
result():获取任务的结果,如果任务未完成则会阻塞直到任务完成。done():判断任务是否完成。
5. 代码示例解析
- 线程池示例:
use_thread_pool()函数展示了如何使用线程池执行任务。任务函数task(n)模拟了一个耗时操作,线程池会并发执行这些任务。 - 进程池示例:
use_process_pool()函数展示了如何使用进程池执行任务。与线程池类似,但适合 CPU 密集型任务。
6. 注意事项
- 线程池:适合 I/O 密集型任务,如网络请求、文件读写等。
- 进程池:适合 CPU 密集型任务,如大量计算、图像处理等。
- 资源管理:使用
with语句可以确保线程池或进程池在使用完毕后正确关闭。
通过 concurrent.futures 模块,可以方便地实现并发编程,提升程序的执行效率。