How to Use Python Queue Module

09/10/2021

Contents

In this article, you will learn how to use Python queue module.

Python Queue Module

The queue module in Python provides several classes for implementing multi-threaded queues that can be used to coordinate the exchange of information between threads. Here are a few examples of how you can use the queue module in Python:

Queue class

This is a simple implementation of a thread-safe queue that can be used to pass messages from one thread to another. Here’s an example:

import queue
import threading

# Create a queue object
q = queue.Queue()

# Define a worker function that takes items from the queue and processes them
def worker():
    while True:
        item = q.get()
        if item is None:
            break
        # Process the item
        print("Processing item:", item)
        q.task_done()

# Start the worker thread
t = threading.Thread(target=worker)
t.start()

# Put items in the queue for the worker to process
for item in range(10):
    q.put(item)

# Wait for all items in the queue to be processed
q.join()

# Stop the worker thread
q.put(None)
t.join()
LifoQueue class

This is a variation of the Queue class that implements a Last-In, First-Out (LIFO) queue. Here’s an example:

import queue

# Create a LIFO queue object
q = queue.LifoQueue()

# Put items in the queue
for item in range(10):
    q.put(item)

# Get items from the queue (in reverse order)
while not q.empty():
    item = q.get()
    print("Processing item:", item)
PriorityQueue class

This is a variation of the Queue class that implements a priority queue, where items are processed in order of priority. Here’s an example:

import queue

# Create a priority queue object
q = queue.PriorityQueue()

# Put items in the queue with different priorities
q.put((1, "low priority item"))
q.put((10, "high priority item"))

# Get items from the queue (in order of priority)
while not q.empty():
    item = q.get()
    print("Processing item:", item[1])

These are just a few examples of how you can use the queue module in Python. For more information, you can refer to the Python documentation: https://docs.python.org/3/library/queue.html