Final answer:
To solve the producer-consumer problem in C, we can use the concept of threads and mutex locks. This program uses two threads - one for the producer and one for the consumer - to access a shared buffer. The mutex lock ensures that only one thread can access the buffer at a time.
Step-by-step explanation:
To solve the producer-consumer problem in C, we can use the concept of threads and mutex locks. Here's an example:
#include
#include
#include
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* producer(void* arg) {
// Produce data and add it to the buffer
pthread_mutex_lock(&mutex);
if (count == BUFFER_SIZE) {
printf("Buffer is full. Producer is waiting.\\");
pthread_mutex_unlock(&mutex);
return NULL;
}
buffer[count] = rand();
count++;
printf("Producer produced an item.\\");
pthread_mutex_unlock(&mutex);
return NULL;
}
void* consumer(void* arg) {
// Consume data from the buffer
pthread_mutex_lock(&mutex);
if (count == 0) {
printf("Buffer is empty. Consumer is waiting.\\");
pthread_mutex_unlock(&mutex);
return NULL;
}
int item = buffer[count - 1];
count--;
printf("Consumer consumed item: %d\\", item);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
// Create producer and consumer threads
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
// Wait for threads to finish
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
In this program, we use two threads: one for the producer and one for the consumer. They both access a shared buffer. The producer produces random data items and adds them to the buffer, while the consumer consumes items from the buffer. The mutex (mutual exclusion) lock is used to synchronize access to the buffer, ensuring that only one thread can access it at a time.