In this simple producer/consumer example it is as if the await queue.put(item)
does not release the event loop to allow the consumer to run until it finished. This results in the producer putting all it's items onto the queue and only then the consumer gets to take them off.
Is that expected?
I get the result that I am looking for if I follow the await queue.put(item)
with await asyncio.sleep(0)
.
The producer then puts 1 item onto the queue and the consumers then takes 1 item off the queue.
I get the same result in Python 3.6.8 and 3.7.2.
import asyncio
async def produce(queue, n):
for x in range(1, n + 1):
print('producing {}/{}'.format(x, n))
item = str(x)
await queue.put(item)
# await asyncio.sleep(0)
await queue.put(None)
async def consume(queue):
while True:
item = await queue.get()
if item is None:
break
print('consuming item {}...'.format(item))
loop = asyncio.get_event_loop()
queue = asyncio.Queue(loop=loop)
producer_coro = produce(queue, 10)
consumer_coro = consume(queue)
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()