英文:
asyncio.gather doesn't execute my task in same time
问题
以下是您要翻译的代码部分:
我正在使用asyncio.gather来运行多个对API的查询。我的主要目标是执行它们而不等待一个完成以启动另一个。
async def main():
order_book_coroutines = [asyncio.ensure_future(get_order_book_list()) for exchange in exchange_list]
results = await asyncio.gather(*order_book_coroutines)
async def get_order_book_list():
print('***1***')
sleep(10)
try:
#执行API查询
except Exception as e:
pass
print('***2***')
if __name__ == "__main__":
asyncio.run(main())
请注意,我没有翻译您的代码,只提供了原始代码的中文版本。
英文:
I am using asyncio.gather to run many query to an API. My main goal is to execute them all without waiting one finish for start another one.
async def main():
order_book_coroutines = [asyncio.ensure_future(get_order_book_list()) for exchange in exchange_list]
results = await asyncio.gather(*order_book_coroutines)
async def get_order_book_list():
print('***1***')
sleep(10)
try:
#doing API query
except Exception as e:
pass
print('***2***')
if __name__ == "__main__":
asyncio.run(main())
My main problem here is the ouput :
***1***
***2***
***1***
***2***
***1***
***2***
I was waiting something like :
***1***
***1***
***1***
***2***
***2***
***2***
There is a problem with my code ? or i miss understood asyncio.gather utility ?
答案1
得分: 2
没有,你没有误解 asyncio.gather
工具。如果你使用 await asyncio.sleep(10)
而不是 time.sleep(10)
,它将按预期显示输出。time.sleep(10)
会阻塞主线程,而 asyncio.sleep
仅会阻塞当前同时运行 order_book_coroutines
列表中下一个 get_order_book_list
协程的协程。
英文:
> Is there a problem with my code? Or I misunderstood the asyncio.gather
utility?
No, you did not. The expected output would be shown if you used await asyncio.sleep(10)
instead of time.sleep(10)
which blocks the main thread for the given time, while the asyncio.sleep
blocks only the current coroutine concurrently running the next get_order_book_list
of the order_book_coroutines
list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论