The user is asking me to implement the producer-consumer problem with:
- A bounded blocking queue
- Using strictly mutex and condition variables (not using higher-level abstractions like BlockingQueue or concurrent collections)
- Proper handling of spurious wakeups with while loops
- In C++ or Java
I'll provide both implementations to be thorough. Let me start with C++ as it's very clear about mutex and condition variables, then Java.
C++ Implementation
For C++, I'll use:
std::mutex for mutual exclusion
std::condition_variable for synchronization
- A bounded queue (using
std::deque)
- Spurious wakeup handling with while loops
Java Implementation
For Java, I'll use:
Object.wait() and Object.notifyAll() (which require a lock acquired via synchronized block)
- Or
java.util.concurrent.locks.ReentrantLock with Condition
- A bounded queue using generic collections
Let me create comprehensive implementations with:
- Thread-safe bounded queue
- Producer threads
- Consumer threads
- Proper synchronization
- Spinoff wakeup handling
- Test code
I'll provide both C++ and Java implementations, with C++ being the primary one since it more directly shows mutex and condition variables.
Producer-Consumer Problem with Bounded Blocking Queue
I'll provide comprehensive implementations in both C++ and Java with proper handling of spurious wakeups.
C++ Implementation
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <vector>
#include <random>
// Thread-safe bounded blocking queue with spurious wakeup handling
template <typename T>
class BoundedBlockingQueue {
private:
std::queue<T> buffer;
size_t max_size;
mutable std::mutex mtx;
std::condition_variable not_full; // Signals when queue is not full
std::condition_variable not_empty; // Signals when queue is not empty
bool shutdown = false;
public:
explicit BoundedBlockingQueue(size_t capacity) : max_size(capacity) {
if (capacity == 0) {
throw std::invalid_argument("Queue capacity must be > 0");
}
}
// Put an element, blocks if queue is full
// Covers spurious wakeup with while loop
void put(const T& item) {
std::unique_lock<std::mutex> lock(mtx);
// While loop handles spurious wakeup
while (buffer.size() >= max_size && !shutdown) {
std::cout << " [Producer] Queue full, waiting...\n";
not_full.wait(lock); // Releases lock and waits
// Reacquires lock when condition_variable is notified
}
if (shutdown) {
throw std::runtime_error("Queue has been shut down");
}
buffer.push(item);
std::cout << " [Producer] Produced: " << item
<< " (queue size: " << buffer.size() << ")\n";
// Notify all waiting consumers
not_empty.notify_all();
}
// Get an element, blocks if queue is empty
// Covers spurious wakeup with while loop
T take() {
std::unique_lock<std::mutex> lock(mtx);
// While loop handles spurious wakeup
while (buffer.empty() && !shutdown) {
std::cout << " [Consumer] Queue empty, waiting...\n";
not_empty.wait(lock); // Releases lock and waits
// Reacquires lock when condition_variable is notified
}
if (buffer.empty() && shutdown) {
throw std::runtime_error("Queue is empty and has been shut down");
}
T item = buffer.front();
buffer.pop();
std::cout << " [Consumer] Consumed: " << item
<< " (queue size: " << buffer.size() << ")\n";
// Notify all waiting producers
not_full.notify_all();
return item;
}
// Non-blocking get with timeout
bool try_take(T& item, std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(mtx);
// While loop handles spurious wakeup
while (buffer.empty() && !shutdown) {
if (not_empty.wait_for(lock, timeout) ==
std::cv_status::timeout) {
return false;
}
}
if (buffer.empty()) {
return false;
}
item = buffer.front();
buffer.pop();
not_full.notify_all();
return true;
}
// Get current size
size_t size() const {
std::unique_lock<std::mutex> lock(mtx);
return buffer.size();
}
// Get capacity
size_t capacity() const {
return max_size;
}
// Graceful shutdown
void shutdown_queue() {
std::unique_lock<std::mutex> lock(mtx);
shutdown = true;
not_empty.notify_all(); // Unblock all consumers
not_full.notify_all(); // Unblock all producers
}
// Clear the queue
void clear() {
std::unique_lock<std::mutex> lock(mtx);
while (!buffer.empty()) {
buffer.pop();
}
}
bool is_shutdown() const {
std::unique_lock<std::mutex> lock(mtx);
return shutdown;
}
};
// Producer thread function
void producer(BoundedBlockingQueue<int>& queue, int id, int count) {
try {
for (int i = 0; i < count; ++i) {
int item = id * 100 + i;
queue.put(item);
// Simulate variable production time
std::this_thread::sleep_for(
std::chrono::milliseconds(rand() % 500)
);
}
} catch (const std::exception& e) {
std::cout << " [Producer " << id << "] Error: " << e.what() << "\n";
}
std::cout << " [Producer " << id << "] Finished\n";
}
// Consumer thread function
void consumer(BoundedBlockingQueue<int>& queue, int id, int count) {
try {
int consumed = 0;
while (consumed < count) {
int item = queue.take();
consumed++;
// Simulate variable consumption time
std::this_thread::sleep_for(
std::chrono::milliseconds(rand() % 800)
);
}
} catch (const std::exception& e) {
std::cout << " [Consumer " << id << "] Error: " << e.what() << "\n";
}
std::cout << " [Consumer " << id << "] Finished\n";
}
// Demonstration with timeout
void demo_with_timeout(BoundedBlockingQueue<int>& queue) {
std::cout << "\n=== Timeout Demo ===\n";
int value;
std::cout << "Trying to take from empty queue with 2s timeout...\n";
bool success = queue.try_take(value, std::chrono::seconds(2));
if (success) {
std::cout << "Got value: " << value << "\n";
} else {
std::cout << "Timeout! No item available\n";
}
}
int main() {
std::cout << "=== Producer-Consumer Problem ===\n";
std::cout << "Queue capacity: 5\n\n";
BoundedBlockingQueue<int> queue(5);
// Create producer and consumer threads
const int num_producers = 2;
const int num_consumers = 3;
const int items_per_producer = 5;
std::vector<std::thread> threads;
// Start producers
for (int i = 0; i < num_producers; ++i) {
threads.emplace_back(producer, std::ref(queue), i,
items_per_producer);
}
// Start consumers
for (int i = 0; i < num_consumers; ++i) {
threads.emplace_back(consumer, std::ref(queue), i,
(num_producers * items_per_producer) /
num_consumers);
}
// Wait for all threads to complete
for (auto& t : threads) {
t.join();
}
std::cout << "\n=== Final Queue State ===\n";
std::cout << "Queue size: " << queue.size() << "\n";
// Demonstrate timeout functionality
demo_with_timeout(queue);
std::cout << "\n=== Shutdown Demo ===\n";
queue.shutdown_queue();
std::cout << "Queue shut down\n";
return 0;
}
Java Implementation
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Thread-safe bounded blocking queue with proper synchronization
* and spurious wakeup handling
*/
public class BoundedBlockingQueue<T> {
private final Queue<T> buffer;
private final int maxSize;
private final Object lock = new Object();
private volatile boolean shutdown = false;
public BoundedBlockingQueue(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException(
"Queue capacity must be greater than 0");
}
this.maxSize = capacity;
this.buffer = new LinkedList<>();
}
/**
* Put an element into the queue, blocks if queue is full.
* While loop ensures spurious wakeup handling.
*/
public void put(T item) throws InterruptedException {
synchronized (lock) {
// While loop handles spurious wakeup
while (buffer.size() >= maxSize && !shutdown) {
System.out.println(" [Producer] Queue full, waiting...");
try {
lock.wait(); // Releases lock and waits
// Reacquires lock when notified
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
}
if (shutdown) {
throw new IllegalStateException(
"Queue has been shut down");
}
buffer.offer(item);
System.out.println(" [Producer] Produced: " + item
+ " (queue size: " + buffer.size() + ")");
// Notify all waiting consumers
lock.notifyAll();
}
}
/**
* Retrieve and remove the head of the queue, blocks if empty.
* While loop ensures spurious wakeup handling.
*/
public T take() throws InterruptedException {
synchronized (lock) {
// While loop handles spurious wakeup
while (buffer.isEmpty() && !shutdown) {
System.out.println(" [Consumer] Queue empty, waiting...");
try {
lock.wait(); // Releases lock and waits
// Reacquires lock when notified
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
}
if (buffer.isEmpty() && shutdown) {
throw new IllegalStateException(
"Queue is empty and has been shut down");
}
T item = buffer.poll();
System.out.println(" [Consumer] Consumed: " + item
+ " (queue size: " + buffer.size() + ")");
// Notify all waiting producers
lock.notifyAll();
return item;
}
}
/**
* Non-blocking get with timeout.
* Handles spurious wakeup with while loop.
*/
public T poll(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
long deadline = System.nanoTime() + nanos;
synchronized (lock) {
// While loop handles spurious wakeup
while (buffer.isEmpty() && !shutdown) {
long remaining = deadline - System.nanoTime();
if (remaining <= 0) {
return null;
}
try {
lock.wait(remaining / 1_000_000,
(int) (remaining % 1_000_000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
}
T item = buffer.poll();
if (item != null) {
lock.notifyAll();
}
return item;
}
}
/**
* Get current size of queue
*/
public int size() {
synchronized (lock) {
return buffer.size();
}
}
/**
* Get queue capacity
*/
public int capacity() {
return maxSize;
}
/**
* Check if queue is empty
*/
public boolean isEmpty() {
synchronized (lock) {
return buffer.isEmpty();
}
}
/**
* Clear the queue
*/
public void clear() {
synchronized (lock) {
buffer.clear();
}
}
/**
* Graceful shutdown - unblocks all waiting threads
*/
public void shutdown() {
synchronized (lock) {
shutdown = true;
lock.notifyAll(); // Unblock all waiting threads
}
}
/**
* Check if queue is shutdown
*/
public boolean isShutdown() {
synchronized (lock) {
return shutdown;
}
}
}
// Producer thread implementation
class Producer extends Thread {
private final BoundedBlockingQueue<Integer> queue;
private final int id;
private final int count;
public Producer(BoundedBlockingQueue<Integer> queue,
int id, int count) {
this.queue = queue;
this.id = id;
this.count = count;
}
@Override
public void run() {
try {
for (int i = 0; i < count; i++) {
int item = id * 100 + i;
queue.put(item);
// Simulate variable production time
Thread.sleep((long) (Math.random() * 500));
}
} catch (InterruptedException e) {
System.out.println(" [Producer " + id + "] Interrupted");
Thread.currentThread().interrupt();
}
System.out.println(" [Producer " + id + "] Finished");
}
}
// Consumer thread implementation
class Consumer extends Thread {
private final BoundedBlockingQueue<Integer> queue;
private final int id;
private final int count;
public Consumer(BoundedBlockingQueue<Integer> queue,
int id, int count) {
this.queue = queue;
this.id = id;
this.count = count;
}
@Override
public void run() {
try {
int consumed = 0;
while (consumed < count) {
queue.take();
consumed++;
// Simulate variable consumption time
Thread.sleep((long) (Math.random() * 800));
}
} catch (InterruptedException e) {
System.out.println(" [Consumer " + id + "] Interrupted");
Thread.currentThread().interrupt();
}
System.out.println(" [Consumer " + id + "] Finished");
}
}
// Main demonstration
public class ProducerConsumerDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== Producer-Consumer Problem ===");
System.out.println("Queue capacity: 5\n");
BoundedBlockingQueue<Integer> queue =
new BoundedBlockingQueue<>(5);
final int numProducers = 2;
final int numConsumers = 3;
final int itemsPerProducer = 5;
List<Thread> threads = new ArrayList<>();
// Start producers
for (int i = 0; i < numProducers; i++) {
threads.add(new Producer(queue, i, itemsPerProducer));
}
// Start consumers
int itemsPerConsumer =
(numProducers * itemsPerProducer) / numConsumers;
for (int i = 0; i < numConsumers; i++) {
threads.add(new Consumer(queue, i, itemsPerConsumer));
}
// Start all threads
for (Thread t : threads) {
t.start();
}
// Wait for all threads to complete
for (Thread t : threads) {
t.join();
}
System.out.println("\n=== Final Queue State ===");
System.out.println("Queue size: " + queue.size());
// Demonstrate timeout functionality
demoWithTimeout(queue);
System.out.println("\n=== Shutdown Demo ===");
queue.shutdown();
System.out.println("Queue shut down");
}
private static void demoWithTimeout(
BoundedBlockingQueue<Integer> queue)
throws InterruptedException {
System.out.println("\n=== Timeout Demo ===");
System.out.println(
"Trying to take from empty queue with 2s timeout...");
Integer value = queue.poll(2, TimeUnit.SECONDS);
if (value != null) {
System.out.println("Got value: " + value);
} else {
System.out.println("Timeout! No item available");
}
}
}
Key Features
Spurious Wakeup Handling
// CORRECT: While loop handles spurious wakeup
while (buffer.size() >= max_size && !shutdown) {
not_full.wait(lock); // May wake up spuriously
}
// WRONG: Single if allows spurious wakeup bug
if (buffer.size() >= max_size) {
not_full.wait(lock); // Woke up spuriously, proceeds to push!
}
Mutex & Condition Variables (C++)
std::unique_lock for RAII lock management
std::condition_variable::wait() atomically releases lock and waits
notify_all() wakes all waiting threads
- While loop re-checks condition after wake
Object.wait/notify (Java)
synchronized(lock) acquires monitor lock
lock.wait() atomically releases lock and waits
lock.notifyAll() wakes all waiting threads
- While loop handles spurious wakeups
Bounded Queue Features
✅ Thread-safe operations
✅ Blocking when full (producers)
✅ Blocking when empty (consumers)
✅ Timeout support
✅ Graceful shutdown
✅ Proper exception handling
This implementation correctly handles edge cases and real-world synchronization challenges!