Три способа выполнить множество задач с asyncio
Функция для примера:
async def do_it(n):
await asyncio.sleep(random.uniform(0.5, 1))
return n
1. Последовательный вызов
async def main():
for i in range(100):
result = await do_it(i)
Такой вызов имеет смысл только тогда, когда результат одной задачи требуется для вызова следующей.
Если они независимы, то это антипаттерн, так как аналогичен простому синхронному вызову по очереди.
2. Упорядоченный результат
async def main():
tasks = [do_it(i) for i in range(100)]
results = await asyncio.gather(*tasks)
Выполняет корутины конкурентно и возвращает результат в виде списка.
Полезен когда требуется получить результаты в том же порядке в котором задачи отправлены.
3. Результат по мере готовности
tasks = [asyncio.create_task(do_it(i)) for i in range(100)]
for cor in asyncio.as_completed(tasks):
result = await cor
Так же выполняет корутины конкурентно, но не гарантирует порядок. Результат возвращается по мере готовности, каждый отдельно.
Полезен когда нужно обработать любой ответ как можно скорее.
#async
"Faites un max de bruit, ne lâchez pas la pression !" - Rima Hassan (via son avocate) depuis la prison de Givon, détenue illégalement par Netanyahu.
Vous étiez encore présents en nombre ce soir Place de la République! On lâche pas !! Force Rima ! Force Gaza !
#StopBlocus#StopGenocide
-----------
On vous a transféré ce message ? Abonnez-vous au canal Telegram de Jean-Luc Mélenchon sur : https://t.me/JLMelenchon
🔴URGENT - Rassemblement pourla libération sans conditions des prisonniers et la fin du blocus à Gaza !
Ce mardi 10 juin à 18h, rendez-vous à la Place de la République à Paris.
Soyons nombreuses et nombreux ! Merci de partager ce message !
#FlottilleDeLaLiberté#FreedomFlotilla#StopGenocide
-------
Plus d'infos : https://t.me/FranceInsoumise
Gaza is being destroyed, and the Arab world is silent!
Israel is raining fire on Gaza day after day.Beneath the bombs and rockets, the ground trembles, but even more, a mother’s heart shakes in fear.
Children no longer ask for toys—they beg for safety.Women don’t seek adornments—they yearn for a chance to survive.
And us?
Most Arab leaders stay mute. Some even shake hands with this oppressor.While the Muslim nation drowns in blood, they’re lost in luxury and self-interest.
But Allah sees.He hears the cries of the oppressed.One day, the tyrants will face justice—no one will escape.If we stay silent today, history will curse us tomorrow.Pray for Gaza, speak up, stand for truth.
#FreePalestine🇵🇸
#StandWithGaza
#StopGenocide
#SaveHumanity