Три способа выполнить множество задач с 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
Ладно, уже только за это взаимодействие можно порекомендовать сообщество дизайнеров Ньюс в телеграме, которое организовал Женя Арутюнов с командой
Продающий лендос с манифестом и промокодами тут
Если что, это ребята, которые когда-то для Додо придумывали смищные фразочки и другие оч человечные взаимодейтсвия)
🎤Ссылки на утро — второй канал
⏲Устойчивый VPN за звезду
#interaction@cogload#copywriting@cogload
🪐 The galaxy Arp 273, located about 300 million light-years away in the constellation Andromeda, is an extraordinary pair of interacting galaxies twisted into a shape that looks like a cosmic rose. One galaxy’s gravity is pulling and warping the other’s spiral arms, creating elegant loops and arcs that reveal the dramatic effects of galactic encounters in deep space. ✨
#galaxies⚡#interaction⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🌍 The geographic shell of the Earth is where the land, water, air, and life all meet and interact. This thin, dynamic layer makes our planet uniquely suited for life to thrive. ✨
#geography⚡#earthshell⚡#interaction⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In Japan, centuries-old forest areas called satoyama are shaped by human care for farming, wood, and water, blending wild nature and villages into landscapes rich in biodiversity and tradition. ✨
#interaction⚡#landscapes⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Indonesia, ancient forests and rice terraces share land with villages, blending wild and human-shaped environments. This mix supports rare wildlife while feeding local communities. ✨
#interaction⚡#landscapes⚡#sustainability⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the Swiss Alps, ancient irrigation channels called "bisses" direct mountain water through villages and fields. These hand-built waterways have shaped both local ecosystems and farming for centuries. ✨
#interaction⚡#society⚡#mountains⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels