Python asyncio.to_thread()方法与ThreadPoolExecutor不同吗?
我看到asyncio.to_thread方法被添加到@Python3.9+,它的描述说它在一个单独的线程上运行阻塞代码,以便立即运行。见下例:Python asyncio.to_thread()方法与ThreadPoolExecutor不同吗?,python,multithreading,asynchronous,Python,Multithreading,Asynchronous,我看到asyncio.to_thread方法被添加到@Python3.9+,它的描述说它在一个单独的线程上运行阻塞代码,以便立即运行。见下例: def blocking_io(): print(f"start blocking_io at {time.strftime('%X')}") # Note that time.sleep() can be replaced with any blocking # IO-bound operation, suc
def blocking_io():
print(f"start blocking_io at {time.strftime('%X')}")
# Note that time.sleep() can be replaced with any blocking
# IO-bound operation, such as file operations.
time.sleep(1)
print(f"blocking_io complete at {time.strftime('%X')}")
async def main():
print(f"started main at {time.strftime('%X')}")
await asyncio.gather(
asyncio.to_thread(blocking_io),
asyncio.sleep(1))
print(f"finished main at {time.strftime('%X')}")
asyncio.run(main())
# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54
通过解释,它似乎使用线程机制,而不是上下文切换或协同路由。这是否意味着它实际上不是异步的?它是否与concurrent.futures.ThreadPoolExecutor中的传统多线程相同?那么,以这种方式使用线程有什么好处呢?to\u thread非常简单。它归结为等待,默认的executor参数为None
事实上,是的,这是传统的多线程,打算在单独线程上运行的代码不是异步的,但to_线程允许您异步等待其结果
还请注意,该函数在当前任务的上下文中运行,因此其值将在func中可用
异步定义到_threadfunc、/、*args、**kwargs:
在单独的线程中异步运行函数*func*。
直接传递为此函数提供的任何*arg和**kwarg
到*func*。此外,当前的:class:`contextvars.Context`也被传播,
允许在中访问主线程中的上下文变量
分开的线。
返回可等待以获得*func*最终结果的协同程序。
loop=events.get\u running\u循环
ctx=contextvars.copy\u上下文
func_call=functools.partialctx.run,func,*args,**kwargs
return wait loop.run_in_executor无,func_调用
to_线程的定义非常简单。它归结为等待,默认的executor参数为None
事实上,是的,这是传统的多线程,打算在单独线程上运行的代码不是异步的,但to_线程允许您异步等待其结果
还请注意,该函数在当前任务的上下文中运行,因此其值将在func中可用
异步定义到_threadfunc、/、*args、**kwargs:
在单独的线程中异步运行函数*func*。
直接传递为此函数提供的任何*arg和**kwarg
到*func*。此外,当前的:class:`contextvars.Context`也被传播,
允许在中访问主线程中的上下文变量
分开的线。
返回可等待以获得*func*最终结果的协同程序。
loop=events.get\u running\u循环
ctx=contextvars.copy\u上下文
func_call=functools.partialctx.run,func,*args,**kwargs
return wait loop.run_in_executor无,func_调用