Три способа выполнить множество задач с 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
🚨*ATTENTION*
*The British chapter of the Antifascist International* calls on the oppressed of the world to stand firmly with Venezuelan 🇻🇪 sovereignty and to denounce *UK complicity* in the imperialist war against *Venezuela*.
All out! Join us!
🗓 10 January ⏰ 1:00pm
🏢 Downing Street
🥁 Bring noise, flags, banners!!
#HandsOffVenezuela
https://antifascistinternational.uk/solidarity-with-the-people-of-the-bolivarian-republic-of-venezuela-and-president-nicolas-maduro-moros/
Erklärung der DKP zu den US-Angriffen gegen Venezuela!
Jetzt lesen unter unsere-zeit.de/haende-weg-von-venezuela-3-4810421/
#handsoffvenezuela#venezuela#usa
Responding to a call from the International People's Assembly, ALBA Movimientos, The Simon Bolivar Institute and The Assembly of Caribbean Peoples, activists worldwide rallied against US intervention in Venezuela and supported its recent presidential election.
From Kinshasa to Seoul, Rome to Luanda, and beyond, demonstrations defended Venezuelan democracy and sovereignty. In cities like Oslo, Vigo, and Pretoria, participants voiced solidarity with the Venezuelan people and the Bolivarian Government and condemned fascism and imperialist actions.
Click here to view the full gallery 👉🏼https://shorturl.at/YV7b0
#handsoffVenezuela#Venezuela#solidarity#internationalpeoplesassembly
🇺🇸🕊️El imperio no habla por su pueblo
⚡️Mientras Trump escala su agresión contra Venezuela, crece la resistencia interna en Estados Unidos. Organizaciones pacifistas protestaron frente al Congreso para denunciar la larga historia de intervenciones ilegales impulsadas desde la Casa Blanca.
📄 Respaldados por más de 15.000firmas, los activistas exigieron apoyo a la Resolución Constitucional 68, que ordena retirar a las Fuerzas Armadas de EE.UU. de Venezuela por carecer de aval legislativo.
👉 Incluso dentro de EE.UU., la guerra pierde legitimidad.
#NoALaGuerra
#TrumpAgresor
#VenezuelaResiste
#PuebloDeEEUUContraLaGuerra
#NoMásIntervenciones
#RespetoAlDerechoInternacional
#AntiImperialismo
#PeaceNotWar
#HandsOffVenezuela