meh*_*meh 4 python python-asyncio
我是一名 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。
根据定义,使用await等待任务main完成。因此,您的代码原样与您上面发布的同步代码没有什么不同。如果您想在等待结果时同时(异步)运行它们,则应该使用asyncio.gatherorasyncio.wait代替。
async def async_io():
tasks = []
for i in range(10):
tasks += [main(i)]
await asyncio.gather(*tasks)
Run Code Online (Sandbox Code Playgroud)
如果您不想等待所有调用main()完成,您也可以只使用asyncio.create_task(main(i)),它会创建一个Task对象并在后台安排其执行。在这种情况下,def async_io()不需要再异步了。
| 归档时间: |
|
| 查看次数: |
1074 次 |
| 最近记录: |