@KIN1991
Python, PHP developer

Почему выпадает ошибка asyncio?

Добрый день!
Разбираюсь с асинхронным программированием и вот не могу понять почему выпадает ошибка:
Task was destroyed but it is pending!
task: <Task pending coro=<TestAsync._consume() running at test_async.py:19> wait_for=<Future cancelled>>

Вот мой код
import asyncio


class TestAsync:

    def __init__(self):
        self._loop = asyncio.get_event_loop()
        self._queue = asyncio.Queue(loop=self._loop)
        self.result = []

    async def _consume(self):
        while True:
            item = await self._queue.get()
            self.result.append(item)
            self._queue.task_done()
            await asyncio.sleep(0.1)

    async def _produce(self):
        for i in range(10):
            await self._queue.put(i ** 2)
        self._queue.task_done()
        await asyncio.sleep(0.2)

    def run(self):
        consumer = asyncio.ensure_future(self._consume(), loop=self._loop)
        self._loop.run_until_complete(self._produce())
        self._loop.run_until_complete(self._queue.join())
        consumer.cancel()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._loop.close()
        return exc_type is None


with TestAsync() as obj:
    obj.run()

print(obj.result)


При этом результат выдается но не полный
[0, 1, 4, 9, 16, 25, 36, 49, 64]
  • Вопрос задан
  • 223 просмотра
Решения вопроса 1
@KIN1991 Автор вопроса
Python, PHP developer
вопрос снимается не правильно реализовал pattern producer/consumer - https://asyncio.readthedocs.io/en/latest/producer_...
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

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