concurrent.futures.Future
是我们用来编写基于OS线程或OS进程以及concurrent.futures
模块提供的其他功能的异步代码的对象。
asyncio.Future
是一个对象,用于基于协程和事物asyncio
模块编写的异步代码编写。
换句话说concurrent.futures
,asyncio
尝试以不同的方式解决相同的任务。解决相同的任务意味着在基于线程/进程的方法和基于协程的方法中,许多事情都将是相似的。例如,看看asyncio.Lock和threading.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