Intermediate LevelPython
How do you build thread-safe Producer-Consumer pipelines using queue.Queue, LifoQueue, and PriorityQueue?
❓ Interview Prompt: Explain `queue.Queue` (FIFO), `LifoQueue` (LIFO Stack), `PriorityQueue`, thread safety, blocking operations, and `task_done()` / `join()`.
The 'queue' module implements multi-producer, multi-consumer thread-safe queues with internal mutex locking:
Key Methods:
•
'q.put(item)': Inserts item into queue (blocks if queue is full).
•
'q.get()': Retrieves item from queue (blocks if queue is empty).
•
'q.task_done()' / 'q.join()': Coordinates pipeline completion across worker threads.
Code Implementation Example
python
from queue import Queue
import threading
work_queue = Queue(maxsize=10)
def worker():
while True:
item = work_queue.get()
print(f'Processing {item}')
work_queue.task_done()
# Start worker thread
threading.Thread(target=worker, daemon=True).start()
work_queue.put('Task 1')
work_queue.put('Task 2')
work_queue.join() # Blocks until all items are processed!💡Building thread-safe Producer-Consumer task queues.
🎯 Interview Key Takeaway
Use queue.Queue for thread-safe Producer-Consumer message passing between worker threads.
#queue#Queue#Producer-Consumer#Thread Safety#Intermediate
Back to all Python Questions→