根据python的异步IO示例:
import asyncio
import time
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
它正在输出下一个错误:
asyncio.to_thread(blocking_io),
AttributeError: module 'asyncio' has no attribute 'to_thread'
此功能是否已被弃用?使用asyncio线程的替代方案是什么
to_thread
仅在python 3.9+中可用,如果您使用的是python 3.8或更早的版本,则可以复制它的source code:此方法将上下文复制到线程(使用集合ContextVars的当前值)
如果您不需要,只需要一行:
有关run_in_executor的详细信息
相关问题 更多 >
编程相关推荐