gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
pyhon sync queue
- User
pyhon sync queue
- Assistant
It looks like you want to work with a synchronized (thread-safe) queue in Python.
Python provides a built-in module called
queuewhich implements multi-producer, multi-consumer queues with synchronization primitives. This module is thread-safe and can be used for communication between threads.Here’s a quick overview and example using
queue.Queuefor a synchronized queue:
Using
queue.Queuefor a Thread-Safe Queueimport queue import threading import time # Create a synchronized queue q = queue.Queue() def producer(): for i in range(5): print(f"Producing {i}") q.put(i) # Thread-safe time.sleep(1) def consumer(): while True: item = q.get() # Thread-safe, blocks if queue is empty if item is None: break # Exit signal print(f"Consumed {item}") q.task_done() # Start threads producer_thread = threading.Thread(target=producer) consumer_thread = threading.Thread(target=consumer) consumer_thread.start() producer_thread.start() producer_thread.join() q.put(None) # Signal consumer to exit consumer_thread.join() print("Done")