Три способа выполнить множество задач с 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
R✨e✨m✨e✨m✨b✨e✨r
Never forget
- Good luck, Have Fun, Don't Die.. 2026 Film putting it right in our faces. Real eyes Realize Real Lies. ..
,•°°•ꨄ•°°•,
✨🌞✨
’•✧•’
( Big Homie )¯\_(ツ)_/¯
All the world is their stage. 🎬
𝐄 𝐍 𝐉 𝐎 𝐘 | 🌟🌟🌿
#Wisdom
It's not what we bought but what we built
It's not what we got but what we shared
It's not our competence but our characters
And it's not our success but our significance
Live a life that matters. Live a life of love.
Unknown
#wisdom
@quietworld🍃
The day the child realizes that all adults are imperfect he becomes an adolescent; the day he forgives them, he becomes an adult; the day he forgives himself he becomes wise.
– Alden N –
#wisdom
@quietworld🍃
We judge people by what they see and hear, but we do not see the qualities that are hidden in their hearts. Avoid suspicion. Let's not say bad things about each other. Let us not gossip or insult.
#wisdom
We can control the words we say, but we can't control what people understand.
We can control what we say to people, but we can't control what other people say to others about us.
That's normal and just a part of life so be it. I'm at peace when I control only what I can control and refuse to take part in things that I cannot control especially those which do not matter at all. ☺️✨🦋
#thoughts#wisdom
@quietworld🍃
To live only for some future goal is shallow. It’s the sides of the mountain that sustain life, not the top.
– Robert M. Prisig
#life#wisdom
@quietworld🍃