Thread-Safe Queues with queue.Queue
`queue.Queue` provides a thread-safe FIFO pipeline with built-in locking. Threads can push items with `.put()` and pull items with `.get()` without manual mutexes 📦.
import queue
q = queue.Queue(maxsize=3)
q.put("job_1")
q.put("job_2")
print(q.get()) # 'job_1' 📦
print(q.get()) # 'job_2' 📦
print(q.empty()) # True ✅
# 54. Thread-Safe Queues with queue.Queue `queue.Queue` provides a thread-safe FIFO pipeline with built-in locking. Threads can push items with `.put()` and pull items with `.get()` without manual mutexes 📦. ```python import queue q = queue.Queue(maxsize=3) q.put("job_1") q.put("job_2") print(q.get()) # 'job_1' 📦 print(q.get()) # 'job_2' 📦 print(q.empty()) # True ✅ ``` If `q.get()` is called on an empty queue, the calling thread automatically blocks until an item is pushed. No busy-waiting spin loops wasting CPU cycles! 📦 --- ### Question What does a consumer thread do by default when calling `.get()` on an empty `queue.Queue`? 🧠- [ ] a. Blocks and sleeps until an item is placed in the queue 📦 - [ ] b. Raises an immediate IndexError - [ ] c. Returns None without waiting - [ ] d. Terminates the consumer thread immediately --- ### Challenge Import `queue`. Initialize `q = queue.Queue()`. Put `'alpha'` and `'beta'`. Retrieve both with `.get()` and print them separated by space. 🎯 <details> <summary>Solution</summary> ```python import queue q = queue.Queue() q.put("alpha") q.put("beta") print(f"{q.get()} {q.get()}") ``` </details>