asyncio.gather不会同时执行我的任务。

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月9日 01:58:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定