Три способа выполнить множество задач с 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
😄Paint
➖➖➖➖➖➖
🔘 The noun paint refers to coloured liquid that makes things look nice. The verb has different meanings. It can mean to put paint on something with a brush.
🔜 I'm going to paint this wall yellow, and this one white.
🔜The table was painted green.
🔘 Paint can also mean to make a picture of something, using paint.
🔜 She painted a portrait of me, it looks great.
🔜 The artist painted the beautiful landscape.
🔘 Paint can also mean to apply a liquid (not just paint) to something with a brush.
🔜 Paint the pastry with egg before putting it in the oven.
🔜 Paint the wood preserver on the fence to protect it.
#Paint👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Paint
➖➖➖➖➖➖
🔘 The noun paint refers to coloured liquid that makes things look nice. The verb has different meanings. It can mean to put paint on something with a brush.
🔜 I'm going to paint this wall yellow, and this one white.
🔜The table was painted green.
🔘 Paint can also mean to make a picture of something, using paint.
🔜 She painted a portrait of me, it looks great.
🔜 The artist painted the beautiful landscape.
🔘 Paint can also mean to apply a liquid (not just paint) to something with a brush.
🔜 Paint the pastry with egg before putting it in the oven.
🔜 Paint the wood preserver on the fence to protect it.
#Paint👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys