Три способа выполнить множество задач с 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
🔥✨Unleash the Power of Aston Martin Valiant!✨🔥
Embark on a journey of power and precision with the Aston Martin Valiant, driven by a formidable 5.2-liter V12 engine with twin turbocharging, delivering an impressive 745 horsepower (compared to 715 in the Valour). Feel the exhilarating torque of 753 Nm propelling you forward with each twist of the throttle. Get ready to ignite your senses!
This fusion of power and performance is harnessed by an exclusive six-speed manual transmission, seamlessly transferring power to the rear wheels, creating an unmatched driving experience. Trust the Aston Martin Valiant to experience the exceptional blend of technology and emotion on the road.
Dive into the true embodiment of power, style, and automotive mastery with the Aston Martin Valiant!
#AstonMartin#Valiant#V12Power#Performance#DrivingExperience
🚗✨Introducing the Speedster 612 TR Teppista!✨🚗
This stunning masterpiece, based on the iconic Ferrari 250 Testarossa from 1957, is now available in the UAE for an astonishing 823 million rubles! 💰🇦🇪
🔍What makes it so special?
- Crafted in 2008 with a sleek carbon body that’s longer and wider than ever! 🖤
- Powered by a roaring V12 engine with a capacity of 5.7 liters! 🏎️💨
A true collector’s dream! 🌟
#Speedster612TR#Ferrari#LuxuryCars#CarCollector#UAE#AutomotiveArt#V12Power#Auto
✨ Introducing the Rolls-Royce Ghost Series II ✨
The updated sedan features a stunning new headlight design and an enlarged grille, reminiscent of the Spectre coupe! 🚗💎 The 22-inch wheels showcase fresh patterns, and a new deep blue shade joins the color palette. 🎨🔵
Inside, experience luxury with a unique bamboo-based fabric, crafted over a year! 🌿🛋️ The media system now operates on the advanced Spirit OS. 📱🎶
Under the hood, the powerful turbocharged V12 engine boasts 563 hp (591 hp in the Black Badge version) and is paired with an 8-speed automatic transmission for smooth rear-wheel drive. 💨⚙️
Elevate your journey with the Ghost Series II! 🌌
#RollsRoyce#GhostSeriesII#Luxury#AutomotiveExcellence#V12Power#Bespoke#EleganceOnWheels#Auto