Три способа выполнить множество задач с 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
🌍 In Chile's Atacama Desert, rare fog called "camanchaca" drifts inland from the Pacific. Some plants here survive by absorbing water directly from this fog, not from rainfall. ✨
#desert⚡#arid⚡#adaptation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some arid desert landscapes feature ancient, dried-up riverbeds called wadis that can flood suddenly after rare rains, quickly turning from bare channels to rushing streams in a matter of hours. ✨
#desert⚡#arid⚡#landscapes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Libya’s Libyan Desert holds sand seas with dunes reaching up to 180 meters tall. These giant dunes constantly shift with the wind, creating landscapes that can look completely different in just a few years. ✨
#desert⚡#dunes⚡#arid⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the Taklamakan Desert of China, some sand dunes reach up to 300 meters tall. Shifting winds keep these giant dunes moving, constantly reshaping the landscape year after year. ✨
#deserts⚡#dunes⚡#arid⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Atacama Desert in Chile is so dry that some weather stations have never recorded rain. Its Mars-like soils are studied by scientists searching for signs of life in extreme environments. ✨
#desert⚡#extreme⚡#arid⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Namib Desert is thought to be the oldest desert on Earth, with arid conditions lasting for at least 55 million years—far longer than any other known desert. ✨
#desert⚡#Namib⚡#arid⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍