Producer-Consumer Pattern with Queues
The Producer-Consumer pattern decouples tasks producing data from workers processing it. A sentinel value (like `None`) signals workers that production has finished 🏭.
import queue, threading
q = queue.Queue()
def producer():
for item in ["task_a", "task_b", None]: # None = stop signal 🛑
q.put(item)
def consumer():
while True:
task = q.get()
if task is None:
break
print(f"Processed: {task} ⚙️")
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start(); t2.start()
t1.join(); t2.join()
# 55. Producer-Consumer Pattern with Queues The Producer-Consumer pattern decouples tasks producing data from workers processing it. A sentinel value (like `None`) signals workers that production has finished 🏭. ```python import queue, threading q = queue.Queue() def producer(): for item in ["task_a", "task_b", None]: # None = stop signal 🛑 q.put(item) def consumer(): while True: task = q.get() if task is None: break print(f"Processed: {task} ⚙️") t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start(); t2.start() t1.join(); t2.join() ``` Using a sentinel `None` guarantees clean worker shutdown without harsh thread termination or dangling background loops! 🏭 --- ### Question What role does a sentinel value like `None` play in a Producer-Consumer queue pipeline? 🧠 - [ ] a. Signals worker threads that all jobs are finished and they can cleanly exit 🛑 - [ ] b. Forces the queue to delete all previously stored items - [ ] c. Restarts the producer thread from index 0 - [ ] d. Clears the operating system cache --- ### Challenge Create a queue `q`. Push `[10, 20, None]`. In a loop, read items; if item is `None` break, else accumulate into sum `total`. Print `total`. 🎯 <details> <summary>Solution</summary> ```python import queue q = queue.Queue() for val in [10, 20, None]: q.put(val) total = 0 while True: item = q.get() if item is None: break total += item print(total) ``` </details>