0% found this document useful (0 votes)
0 views

5)Producerconsumer

This C program implements a producer-consumer problem using semaphores for synchronization. It defines a buffer of size N, where the producer generates items and the consumer consumes them, ensuring thread-safe operations. The program creates two threads for the producer and consumer, manages access to the buffer with semaphores, and cleans up resources at the end.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

5)Producerconsumer

This C program implements a producer-consumer problem using semaphores for synchronization. It defines a buffer of size N, where the producer generates items and the consumer consumes them, ensuring thread-safe operations. The program creates two threads for the producer and consumer, manages access to the buffer with semaphores, and cleans up resources at the end.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <stdio.

h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define N 5 // Buffer size


sem_t mutex, empty, full;
int buffer[N];
int in = 0, out = 0;

void* producer(void* arg) {


for (int i = 0; i < 10; i++) {
sem_wait(&empty);
sem_wait(&mutex);
buffer[in] = i;
printf("Produced: %d\n", buffer[in]);
in = (in + 1) % N;
sem_post(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}

void* consumer(void* arg) {


for (int i = 0; i < 10; i++) {
sem_wait(&full);
sem_wait(&mutex);
int item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % N;
sem_post(&mutex);
sem_post(&empty);
sleep(1);
}
return NULL;
}

int main() {
pthread_t p, c;
sem_init(&mutex, 0, 1);
sem_init(&empty, 0, N);
sem_init(&full, 0, 0);

pthread_create(&p, NULL, producer, NULL);


pthread_create(&c, NULL, consumer, NULL);

pthread_join(p, NULL);
pthread_join(c, NULL);

sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}

You might also like