PYTHON

Implement First-In, First-Out (FIFO) Queues with `queue.Queue`

Understand how to use Python's `queue.Queue` for thread-safe, first-in, first-out data structures, essential for producer-consumer patterns and managing asynchronous tasks in web applications.

import queue
import threading
import time

# Create a FIFO queue
my_queue = queue.Queue(maxsize=3)

def producer():
    for i in range(5):
        try:
            item = f"item_{i}"
            my_queue.put(item, timeout=1) # Block if queue is full
            print(f"Producer: Put {item}")
            time.sleep(0.1)
        except queue.Full:
            print(f"Producer: Queue is full, skipped item_{i}")

def consumer():
    while True:
        try:
            item = my_queue.get(timeout=1) # Block if queue is empty
            print(f"Consumer: Got {item}")
            my_queue.task_done() # Mark task as complete
            time.sleep(0.5)
        except queue.Empty:
            print("Consumer: Queue is empty, exiting.")
            break

# Start producer and consumer threads
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)

producer_thread.start()
consumer_thread.start()

# Wait for the producer to finish
producer_thread.join()
# Wait for all tasks in the queue to be processed
my_queue.join()
print("All tasks processed.")
How it works: The `queue` module provides thread-safe classes implementing multi-producer, multi-consumer queues, crucial for concurrent programming. `queue.Queue` specifically implements a First-In, First-Out (FIFO) data structure. `put()` adds items, `get()` retrieves them, and `task_done()` combined with `join()` allows waiting until all items previously put into the queue have been retrieved and processed, ensuring all work is completed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs