温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python 3.x - Can concurrent.futures.Future be converted to asyncio.Future?
python-3.x python-asyncio python-multithreading concurrent.futures

python 3.x - 可以将current.futures.Future转换为asyncio.Future吗?

发布于 2020-03-28 23:33:38

asyncio多年编写多线程代码后,我正在练习

注意到我觉得很奇怪的东西。无论是在asyncioconcurrent有一个Future对象。

from asyncio import Future
from concurrent.futures import Future

猜猜每个人都有自己的角色。

我的问题是我是否可以转移concurrent.future.Futureasyncio.Future(或相反)?

查看更多

查看更多

提问者
Aaron_ab
被浏览
40
Mikhail Gerasimov 2019-01-09 03:51

concurrent.futures.Future是我们用来编写基于OS线程或OS进程以及concurrent.futures模块提供的其他功能的异步代码的对象

asyncio.Future是一个对象,用于基于协程和事物asyncio模块编写的异步代码编写

换句话说concurrent.futuresasyncio尝试以不同的方式解决相同的任务。解决相同的任务意味着在基于线程/进程的方法和基于协程的方法中,许多事情都将是相似的。例如,看看asyncio.Lockthreading.Lock-相似,但不同。

不同的类似对象之间是否可能过渡?不,这不对。

asyncio与基于线程的模块之间的本质区别使合作无法实现:

  • 在异步中,您应该await挂起执行流程并允许其他协程同时执行。

  • 在基于线程的模块中,通过挂起整个线程来挂起执行流程。

例如,当您编写基于线程的代码时,您将编写:

future = concurrent.futures.Future()
# ...
result = future.result()  # acts like time.sleep blocking whole thread

但是在异步中,您不应阻塞线程,而应将控制权返回给事件循环:

future = asyncio.Future()
# ...
result = await future  # block current execution flow returning control to event loop 
                       # without blocking thread,
                       # current flow will be resumed later