Три способа выполнить множество задач с 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 2023, explorers finished mapping over 75% of the world’s seafloor in high detail, uncovering thousands of undersea mountains and canyons hidden beneath the oceans. ✨
#exploration⚡#mapping⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Over 80% of Earth’s ocean remains unmapped and unexplored by humans. Modern sonar and robotic submersibles are revealing new mountains, trenches, and species with every deep-sea journey. ✨
#exploration⚡#ocean⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The first map to show the Americas as a separate continent was made by German cartographer Martin Waldseemüller in 1507. It’s where the name “America” first appeared on a world map. ✨
#cartography⚡#history⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In 2022, explorers used sonar to map a hidden undersea volcano off Madagascar’s coast, revealing a peak 800 meters tall that was completely unknown before their expedition. ✨
#exploration⚡#discovery⚡#oceans⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 While mapping the ocean floor in 1947, researchers aboard HMS Challenger discovered the Mid-Atlantic Ridge, revealing Earth's largest mountain range hidden underwater. This seismic finding triggered the theory of plate tectonics—explaining how continents drift. The ridge stretches for over 16,000 kilometers beneath the Atlantic Ocean. ✨
#discovery⚡#geology⚡#oceanography
👉subscribe Interesting Planet
👉more Channels