This section summarizes key concepts from the lecture on synchronization tools, specifically focusing on the Producer-Consumer Problem, Race Conditions, the Critical Section Problem, and solutions like Peterson's Algorithm and Mutex Locks. The notes also include examples implemented in C where applicable.
The Producer-Consumer Problem involves two entities: a producer that generates data and a consumer that processes that data. The two entities share a buffer, and synchronization is required to ensure:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0; // Number of items in the buffer
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
void* producer(void* arg) {
int item;
while(1) {
item = rand(); // Produce an item
sem_wait(&empty); // Wait if buffer is full
pthread_mutex_lock(&mutex); // Acquire the lock
buffer[count++] = item; // Add item to the buffer
pthread_mutex_unlock(&mutex); // Release the lock
sem_post(&full); // Signal that the buffer is not empty
}
}
void* consumer(void* arg) {
int item;
while(1) {
sem_wait(&full); // Wait if buffer is empty
pthread_mutex_lock(&mutex); // Acquire the lock
item = buffer[--count]; // Remove item from the buffer
pthread_mutex_unlock(&mutex); // Release the lock
sem_post(&empty); // Signal that the buffer is not full
// Consume the item
}
}
int main() {
pthread_t prod, cons;
sem_init(&empty, 0, BUFFER_SIZE); // Buffer starts as empty
sem_init(&full, 0, 0); // Buffer starts with no full slots
pthread_mutex_init(&mutex, NULL);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}