回答我的意见:
async
不会使同步Python函数自动异步;
异步
真的是一种合作多任务处理的形式。
下面是一个简化的例子
f
执行异步工作(以
asyncio.sleep
和
f2
进行同步工作(以
time.sleep
).
import asyncio
import time
async def f(name: str) -> None:
for x in range(3):
print(f"{name} will sleep")
await asyncio.sleep(0.5)
print(f"{name} woke up!")
async def f2(name: str) -> None:
for x in range(3):
print(f"{name} will sleep (2)")
time.sleep(0.5)
print(f"{name} woke up (2)!")
async def main() -> float:
await asyncio.gather(
f("Hernekeitto"),
f("Viina"),
f("Teline"),
)
print("----")
await asyncio.gather(
f2("Johannes"),
f2("Appelsiini"),
f2("Kuutio"),
)
if __name__ == "__main__":
asyncio.run(main())
这会打印出以下内容:
Hernekeitto will sleep
Viina will sleep
Teline will sleep
Hernekeitto woke up!
Hernekeitto will sleep
Viina woke up!
Viina will sleep
Teline woke up!
Teline will sleep
Hernekeitto woke up!
Hernekeitto will sleep
Viina woke up!
Viina will sleep
Teline woke up!
Teline will sleep
Hernekeitto woke up!
Viina woke up!
Teline woke up!
----
Johannes will sleep (2)
Johannes woke up (2)!
Johannes will sleep (2)
Johannes woke up (2)!
Johannes will sleep (2)
Johannes woke up (2)!
Appelsiini will sleep (2)
Appelsiini woke up (2)!
Appelsiini will sleep (2)
Appelsiini woke up (2)!
Appelsiini will sleep (2)
Appelsiini woke up (2)!
Kuutio will sleep (2)
Kuutio woke up (2)!
Kuutio will sleep (2)
Kuutio woke up (2)!
Kuutio will sleep (2)
Kuutio woke up (2)!
正如您所看到的,在第一种情况下,三个异步函数调用能够并行地完成它们的工作(但总有一种模式
woke up! will sleep
,因为没有
await
在两个打印之间(当它们循环运行时)。
在第二种情况下,函数是串行运行的,因为没有
等候
在里面
f2
这将允许其他异步协同程序运行。
如评论中所述,您可以使用
loop.run_in_executor()
在中运行同步函数
concurrent.futures.Executor
(通常为
ThreadPoolExecutor
),所以它在不同的线程(或进程)中运行,结果可能是
等候
预计起飞时间。