CodeBlanks Logo Icon CodeBlanks

Queue

Learn producer-consumer with asyncio.Queue.

Queue

asyncio.Queue provides safe data passing between coroutines. A producer puts data with put; a consumer takes it with get. One waits while the other works.

import asyncio

q = asyncio.Queue()
await q.put(1)
value = await q.get()

Queue is used for buffered communication. If the producer is fast and the consumer is slow, the queue acts as a buffer; and vice versa. When full, put waits; when empty, get waits.

Producer-consumer pattern

Queue implements the classic producer-consumer pattern. A producer coroutine generates data and puts it in the queue with await q.put(item); a consumer takes data with await q.get() and processes it.

When the producer finishes, it can put a sentinel like q.put(None); the consumer stops on seeing it. Multiple consumers are supported; each runs in a separate Task.

Queue makes this pattern safe and scalable in asyncio; no lock is needed.

Practice Producer-consumer with Queue

Start with import asyncio. The function async def producer(q) does await q.put(42) and await q.put(None). The function async def consumer(q) reads value = await q.get() and returns it. Inside async def main() build q = asyncio.Queue(), call asyncio.gather(producer(q), consumer(q)) and return it. Add print(asyncio.run(main())).

Starter code

main.py
# import the asyncio module
# producer(q): put 42 and None
# consumer(q): get the value and return it
# main: create Queue, run both via gather, print result

Sample solution

main.py
import asyncio

async def producer(q):
    await q.put(42)
    await q.put(None)

async def consumer(q):
    value = await q.get()
    return value

async def main():
    q = asyncio.Queue()
    return await asyncio.gather(producer(q), consumer(q))

print(asyncio.run(main()))

Expected output

[None, 42]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Queue methods

Term Meaning
q.put(item) Puts data
q.get() Gets data
q.qsize() Returns size
await q.put Waits for room

2 What does await q.get() do when the Queue is empty?

  • Returns None immediately
  • Raises an error
  • Closes the program
  • Waits until data arrives Correct answer

Explanation: q.get() waits until data arrives; await frees the event loop.

3 Queue import and definition

Question
import asyncio

q = asyncio.____()
Answer
import asyncio

q = asyncio.Queue()

Explanation: asyncio.Queue() creates a new queue.

All lessons in Advanced