我是一名 Python 初学者,从https://www.youtube.com/watch?v=iG6fr81xHKA&t=269s获取有关 asyncio 强大功能的信息,我尝试使用所示的示例并将其重新调整用途以执行 10 次。这是一个代码片段
def main(x):
print("Hello")
time.sleep(3)
print("World!")
Run Code Online (Sandbox Code Playgroud)
因此,我尝试以异步方式执行此操作,但它不会异步执行。到目前为止,这是我尝试过的。我究竟做错了什么?
import time
import asyncio
async def main(x):
print(f"Starting Task {x}")
await asyncio.sleep(3)
print(f"Finished Task {x}")
async def async_io():
for i in range(10):
await main(i)
if __name__ == "__main__":
start_time = time.perf_counter()
asyncio.run(async_io())
print(f"Took {time.perf_counter() - start_time} secs")
Run Code Online (Sandbox Code Playgroud)
我还尝试在 asyncio 中使用queue_task。