Три способа выполнить множество задач с 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
🌍 The world’s biggest human migration still happens every year in China, as hundreds of millions travel during Lunar New Year— the largest annual movement of people on Earth. ✨
#migration⚡#population⚡#movement⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2022, the number of international migrants reached an estimated 281 million—more than triple the figure from 1970—making up 3.6% of the world’s total population today. ✨
#migration⚡#demographics⚡#movement⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Since the 1990s, the number of people living outside their birthplace has more than doubled, with most international migration now happening between countries in Asia and Europe. ✨
#migration⚡#demography⚡#movement⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Tokyo’s Shibuya Crossing is one of the busiest pedestrian intersections in the world, where as many as 3,000 people can cross with every green light, illustrating dense urban flow. ✨
#city⚡#infrastructure⚡#movement⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍