Три способа выполнить множество задач с 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
😄Nice
➖➖➖➖➖➖
🔘Nice has a positive meaning and can be similar to good, pleasant or enjoyable.
🔜 We had a really nice time with the monkeys at the zoo.
🔜 It was so nice to see you!
🔘 The negative is also common.
🔜 The weather isn't nice today. Take a coat with you.
🔘We use nice to describe people who are kind, polite or friendly.
🔜 He lent you his phone? What a nice guy.
🔜 I love seeing Susy. She's a really nice lady.
#Nice👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Nice
➖➖➖➖➖➖
🔘Nice has a positive meaning and can be similar to good, pleasant or enjoyable.
🔜 We had a really nice time with the monkeys at the zoo.
🔜 It was so nice to see you!
🔘 The negative is also common.
🔜 The weather isn't nice today. Take a coat with you.
🔘We use nice to describe people who are kind, polite or friendly.
🔜 He lent you his phone? What a nice guy.
🔜 I love seeing Susy. She's a really nice lady.
#Nice👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys