Три способа выполнить множество задач с 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
🪙 32,137 #BTC ($2.18 billion) went from the wallet of the #Mt․Gox exchange that collapsed in 2014 to an unknown address — the market reacted with a drop, suggesting that payments to the exchange's creditors could begin at any moment.
⚫️The Black Swan arrived unexpectedly... wait for new comments, despite the unpleasant surprise, the situation may become an opportunity to enter the market and make money on non-negative growth.
😙 The reasons for the fall of the # bitcoin exchange rate below $61,000
The unemployment rate was 4.3%, which is higher than expected, indicating a possible recession
The Bank of Japan raised the interest rate for the first time in 17 years, which led to an outflow of investments from risky assets
Increased geopolitical tensions (fear of a major world war)
😏Continued distribution of #BTC from #Mt.Gox and #Genesis