The producer-consumer problem
What you'll learn: How to synchronize two types of threads that must cooperate using a shared buffer without losing data or crashing.
The assembly line analogy
Imagine a bakery. You have a Baker (the Producer) and a Cashier (the Consumer). Between them sits a small cooling rack that holds exactly five donuts.
If the rack is full, the Baker must stop and wait; otherwise, they’d be throwing donuts onto the floor. If the rack is empty, the Cashier must stop and wait; they can't sell air to a customer. This "rack" is a shared buffer in memory. The challenge is ensuring the Baker and Cashier don't grab for the same donut at the exact same time and that they know when to sleep or wake up.
Solving it with Mutexes and Semaphores
To solve this in C, we use two tools: Mutexes (to ensure only one thread touches the rack at a time) and Semaphores (to track how many spots are full or empty).
- Empty Semaphore: Starts at the buffer size (e.g., 5). It tells the Producer how many donuts they can still make.
- Full Semaphore: Starts at 0. It tells the Cashier how many donuts are ready to be sold.
The Logic in Code
Here is how these threads interact using the pthread library logic:
#include <pthread.h>
#include <semaphore.h>
int buffer[5];
int count = 0;
sem_t empty; // Tracks empty slots
sem_t full; // Tracks filled slots
pthread_mutex_t mutex;
void* producer(void* arg) {
while (1) {
int item = 1; // Produce a "donut"
sem_wait(&empty); // Wait for an empty slot
pthread_mutex_lock(&mutex); // Lock the rack
buffer[count++] = item; // Add donut to rack
pthread_mutex_unlock(&mutex); // Unlock the rack
sem_post(&full); // Signal that a donut is ready
}
}
void* consumer(void* arg) {
while (1) {
sem_wait(&full); // Wait for a full slot
pthread_mutex_lock(&mutex); // Lock the rack
int item = buffer[--count]; // Take donut from rack
pthread_mutex_unlock(&mutex); // Unlock the rack
sem_post(&empty); // Signal that a slot is now free
}
}
Why this matters
Without the semaphores, the Consumer might try to access buffer[-1] because it didn't know the rack was empty, causing a segmentation fault. Without the mutex, the Baker and Cashier might both try to update the count variable at the exact same microsecond, leading to corrupted data. This pattern is the foundation of how operating systems handle everything from keyboard inputs to network packets.
Key takeaway
The producer-consumer pattern uses semaphores to signal availability and mutexes to protect data integrity during the hand-off.