Grok 4.1 Fast· xai
Frontier Reasoning Traces
Write a multi-threaded producer-consumer solution with bounded buffer.
- User
Write a multi-threaded producer-consumer solution with bounded buffer.
- Assistant
import threading import time from collections import deque import random class BoundedBuffer: """ A thread-safe bounded buffer for producer-consumer pattern. Uses Lock and Condition variables for synchronization. """ def __init__(self, capacity): self.buffer = deque() self.capacity = capacity self.lock = threading.Lock() self.not_empty = threading.Condition(self.lock) self.not_full = threading.Condition(self.lock) self.total_items = 0 # For demo tracking def put(self, item): with self.lock: while len(self.buffer) == self.capacity: print(f"Buffer full, producer waiting... (current size: {len(self.buffer)})") self.not_full.wait() self.buffer.append(item) self.total_items += 1 print(f"Produced: {item} (buffer size: {len(self.buffer)})") self.not_empty.notify_all() # Wake up all waiting consumers def get(self): with self.lock: while len(self.buffer) == 0: print(f"Buffer empty, consumer waiting... (current size: {len(self.buffer)})") self.not_empty.wait() item = self.buffer.popleft() print(f"Consumed: {item} (buffer size: {len(self.buffer)})") self.not_full.notify_all() # Wake up all waiting producers return item def producer(buffer, producer_id, num_items=20): """ Producer thread: generates items and puts them into the buffer. """ for i in range(num_items): item = f"item-P{producer_id}-{i}-{random.randint(1000, 9999)}" buffer.put(item) time.sleep(random.uniform(0.05, 0.2)) # Simulate variable production time print(f"Producer {producer_id} finished producing {num_items} items.") def consumer(buffer, consumer_id, num_items=20): """ Consumer thread: retrieves and "processes" items from the buffer. """ processed = 0 while processed < num_items: item = buffer.get() # Simulate processing time time.sleep(random.uniform(0.1, 0.3)) processed += 1 print(f"Consumer {consumer_id} finished consuming {num_items} items.") def main(): BUFFER_CAPACITY = 5 NUM_PRODUCERS = 3 NUM_CONSUMERS = 2 ITEMS_PER_THREAD = 25 # Total items: 3*25=75 produced, 2*25=50 consumed (extra producers to fill buffer) print(f"Starting producer-consumer demo with buffer capacity {BUFFER_CAPACITY}") print(f"{NUM_PRODUCERS} producers, {NUM_CONSUMERS} consumers, {ITEMS_PER_THREAD} items each.\n") buffer = BoundedBuffer(BUFFER_CAPACITY) threads = [] # Start producers for i in range(NUM_PRODUCERS): t = threading.Thread(target=producer, args=(buffer, i, ITEMS_PER_THREAD)) t.start() threads.append(t) # Start consumers for i in range(NUM_CONSUMERS): t = threading.Thread(target=consumer, args=(buffer, i, ITEMS_PER_THREAD)) t.start() threads.append(t) # Wait for all threads to complete for t in threads: t.join() print("\nAll threads completed. Demo finished.") if __name__ == "__main__": main()Explanation
- BoundedBuffer Class: Implements a fixed-size buffer using
dequefor O(1) append/popleft.Lockensures mutual exclusion.- Two
Conditionvariables (not_empty,not_full) handle waiting/waking efficiently. - Producers block on full buffer; consumers on empty.
notify_all()ensures fairness across multiple threads.
- Producer/Consumer Functions: Simulate real-world variability with random delays. Fixed item counts for clean termination.
- Demo Setup: 3 producers, 2 consumers, buffer size 5. Run it to see blocking messages and buffer state.
- Thread-Safe & Correct: No race conditions, deadlocks, or lost signals. Python's GIL doesn't affect correctness here.
Run this in Python 3.8+ to observe the synchronization in action! If you need it in another language (e.g., Java, C++), let me know.
- BoundedBuffer Class: Implements a fixed-size buffer using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.