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

Program-3

Uploaded by

darshangowda0525
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Program-3

Uploaded by

darshangowda0525
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

/*3.Develop a C program to simulate producer-consumer problem using semaphores.

*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 20

sem_t empty, full;


int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int size = 50;

void* producer(void* arg) {


int item = 1;
while (1) {
sem_wait(&empty);
buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
item++;
sem_post(&full);
if (item > size) {
break;
}
}
printf("Sending completed\n ");
pthread_exit(NULL);
}

void* consumer(void* arg) {


int item;
while (1) {
sem_wait(&full);
item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
sem_post(&empty);
if (item == size) {
printf("Received all");
break;
}
}
pthread_exit(NULL);
}

int main() {
pthread_t producer_thread, consumer_thread;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}

You might also like