ermek6
@ermek6
::Живу с удовольствием::

Как обработать массив данных асинхронно?

Всем привет. Разбираюсь с асинхронным программированием. Скажите, как правильно обработать массив данных?

Я вижу только такой способ (см # async process):

import asyncio
from asyncio import TimeoutError
import time


async def some_function(input: str, index):
    await asyncio.sleep(4)
    print('func finished')
    input[index] = f'New value of {input[index]}'
    return input[index]


async def main():
    # 'sync' process
    print(time.strftime('%X'))
    await asyncio.sleep(1)
    print("hello")
    await asyncio.sleep(1)
    print('world')
    print(await some_function(['input value'], 0))
    print(time.strftime('%X'))

    # async process
    data = ['input 1', 'input 2', 'input 3', 'input 4', 'input 5']

    tasks = []
    tasks.append(asyncio.create_task(some_function(data, 0)))
    tasks.append(asyncio.create_task(some_function(data, 1)))
    tasks.append(asyncio.create_task(some_function(data, 2)))
    tasks.append(asyncio.create_task(some_function(data, 3)))
    tasks.append(asyncio.create_task(some_function(data, 4)))
    try:
        await asyncio.wait_for(asyncio.gather(*tasks), 5)
        for element in data:
            print(f'Result: {element}')
    except TimeoutError:
        print("Timeout (")

    print(time.strftime('%X'))



asyncio.run(main())
  • Вопрос задан
  • 162 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы