The queue module in Python provides several classes for multi-producer, multi-consumer queues. It is especially useful in threaded programming.
Here’s a simple example on how you can use the Queue class:
```
import queue
import threading
def worker(q): while True: item = q.get() if item is None: break
print(f’Working on {item}’) q.task_done()q = queue.Queue()
thread = threading.Thread(target=worker, args=(q,))
thread.start()
In this example, we have a single worker thread that consumes some data from a queue. We put some numbers (0 to 4) into the queue and for each item we tell the worker to process it by calling `q.put(item)`.
Once all items have been processed we call `q.join()` to block until all items have been gotten and processed.
We can stop the worker by putting `None` in the queue and the worker breaks its loop when it retrieves `None`.
More informations:
- `queue.Queue(maxsize)`: Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached.
- `Queue.qsize()`: Returns the approximate size of the queue.
- `Queue.empty()`: Return True if the queue is empty.
- `Queue.full()`: Return True if the queue is full.
- `Queue.put(item, block=True, timeout=None)`: Put item into the queue.
- `Queue.get(block=True, timeout=None)`: Remove and return an item from the queue.
- `Queue.task_done()`: Indicate that a formerly enqueued task is complete.
- `Queue.join()`: Blocks until all items in the queue have been gotten and processed.