Три способа выполнить множество задач с 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 IMAGES | Venezuela Challenges Eurocentric Narratives in International Book Fair
President Nicolás Maduro inaugurated the 21st edition of the Venezuelan International Book Fair (FILVEN), announcing a new initiative to distribute printed books in schools nationwide.
The event, held in Caracas, features Egypt as the guest of honor, commemorating 75 years of diplomatic relations. With 18 publishers from 10 countries, FILVEN runs through July 13 before continuing across other Venezuelan states.
Follow the link to check out our gallery: https://venezuelanalysis.com/images/venezuela-challenges-eurocentric-narratives-in-international-book-fair/
#BookFair#Culture
Venezuela Honors South Africa at the 20th International Book Fair
At Venezuela’s 20th International Book Fair, South Africa was honored with 18 authors, and Nelson Mandela’s legacy was celebrated. The event also featured Jorge Ramos Tolosa’s book on Palestine.
Don’t miss out on the gallery by clicking here 👉🏼https://shorturl.at/PSCso
#bookfair#filven#filven2024#venezuela
📚Book Fair at Green University
📖A book fair was held at the university, bringing together students, faculty, and book lovers in a lively academic atmosphere. The event offered a wide selection of literature, encouraged reading culture, and created a space for meaningful exchange of ideas.
#BookFair#ReadingCulture#StudentLife#LoveForBooks
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube