K
K
KIN19912019-03-30 20:31:57
Python
KIN1991, 2019-03-30 20:31:57

Why is an asyncio error thrown?

Good afternoon!
I understand asynchronous programming and now I can’t understand why the error occurs:

Task was destroyed but it is pending!
task: <Task pending coro=<TestAsync._consume() running at test_async.py:19> wait_for=<Future cancelled>>

Here is my code
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)

In this case, the result is given but not complete
[0, 1, 4, 9, 16, 25, 36, 49, 64]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
KIN1991, 2019-03-30
@KIN1991

the question is removed not correctly implemented pattern producer/consumer - https://asyncio.readthedocs.io/en/latest/producer_...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question