Producer-Consumer Problem (pthread)
// Producer-Consumer Problem
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 5
int buffer = 0; // Single shared buffer
pthread_mutex_t mutex;
void producer()
{ pthread_mutex_lock(&mutex);
if
(buffer < BUFFER_SIZE)
{ // Check if buffer
is not full
buffer++; // Produce (increment)
printf("Producer produced, buffer: %d\n", buffer);
} else
{ printf("Buffer is full,
cannot produce.\n"); }
pthread_mutex_unlock(&mutex);
}
void consumer()
{
pthread_mutex_lock(&mutex);
if
(buffer > 0)
{ // Check if buffer
is not empty
buffer--; // Consume (decrement)
printf("Consumer consumed, buffer: %d\n", buffer);
}
else
{
printf("Buffer is empty, cannot consume.\n");
}
pthread_mutex_unlock(&mutex);
}
int main()
{ int
choice;
pthread_mutex_init(&mutex, NULL);
while (1)
{
printf("Enter 1 for producer, 2 for consumer, 3 for exit: ");
scanf("%d", &choice);
if (choice == 1)
{
producer(); // Directly call producer function
}
else if (choice == 2)
{
consumer(); // Directly call consumer function
}
else if (choice == 3)
{
break;
}
else
{
printf("Invalid choice, please try again.\n");
}
}
pthread_mutex_destroy(&mutex);
return 0; }
Comments
Post a Comment