请说明 asyncio 中的 Future 和 concurrent.futures.Future 的区别,并举例说明它们的适用场景?
在 Python 中,asyncio.Future 和 concurrent.futures.Future 是两个不同的类,它们分别用于异步编程和并发编程,虽然名字相似,但在设计、用途和实现上有显著的区别。以下是它们的区别和适用场景的详细说明,并附上示例。
1. asyncio.Future
asyncio.Future 是 asyncio 模块提供的类,专为异步编程设计。它表示一个异步操作的未来结果,通常与 async/await 语法结合使用。
特点:
- 基于事件循环 (
event loop),适用于单线程的异步 I/O 操作。 - 通过
await关键字获取结果,不能直接调用阻塞方法。 - 支持回调机制,通过
.add_done_callback()方法添加回调函数。
示例:
import asyncio
async def main():
# 创建一个 asyncio.Future
future = asyncio.Future()
# 设置未来结果
future.set_result("Hello, asyncio.Future!")
# 通过 await 获取结果
result = await future
print(result) # 输出: Hello, asyncio.Future!
asyncio.run(main())
适用场景:
- 异步 I/O 操作,如网络请求(
aiohttp)、数据库查询(asyncpg)。 - 需要与其他异步任务协作的场景,比如多个任务并行执行并通过
asyncio.gather收集结果。
2. concurrent.futures.Future
concurrent.futures.Future 是 concurrent.futures 模块提供的类,专为多线程或多进程的并发编程设计。它表示一个并发任务的未来结果,通常与 ThreadPoolExecutor 或 ProcessPoolExecutor 结合使用。
特点:
- 基于线程或进程,适用于 CPU 密集型或阻塞 I/O 操作。
- 通过
.result()方法获取结果,会阻塞当前线程直到结果就绪。 - 支持回调机制,通过
.add_done_callback()方法添加回调函数。
示例:
from concurrent.futures import ThreadPoolExecutor
def task():
return "Hello, concurrent.futures.Future!"
def main():
with ThreadPoolExecutor() as executor:
# 提交任务并获取 Future 对象
future = executor.submit(task)
# 阻塞等待结果
result = future.result()
print(result) # 输出: Hello, concurrent.futures.Future!
main()
适用场景:
- CPU 密集型任务,如大型计算任务。
- 阻塞 I/O 操作,如同步的 HTTP 请求或文件读写。
3. 主要区别总结
| 特性 | asyncio.Future | concurrent.futures.Future |
|---|---|---|
| 设计目标 | 异步编程 | 并发编程 |
| 依赖模块 | asyncio | concurrent.futures |
| 底层实现 | 事件循环 (event loop) | 线程或进程 (ThreadPoolExecutor 等) |
| 获取结果方式 | await future | future.result() |
| 阻塞与非阻塞 | 非阻塞 | 阻塞 |
| 适用任务类型 | I/O 密集型 | CPU 密集型或阻塞 I/O |
| 回调机制 | 支持 .add_done_callback() | 支持 .add_done_callback() |
4. 混合使用场景
在实际开发中,可能需要同时使用两者。例如,在异步代码中调用一个阻塞的同步函数,可以使用 asyncio.run_in_executor 将其包装为 asyncio.Future。
示例:
import asyncio
from concurrent.futures import ThreadPoolExecutor
def blocking_task():
return "Hello from blocking task!"
async def main():
loop = asyncio.get_running_loop()
# 将阻塞任务提交到线程池,返回 asyncio.Future
future = loop.run_in_executor(None, blocking_task)
# 异步等待结果
result = await future
print(result) # 输出: Hello from blocking task!
asyncio.run(main())