BCS303 Program 3

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

PROGRAM:

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

#define BUFFER_SIZE 10

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

sem_t empty;
sem_t full;
sem_t mutex;

void* producer(void* arg) {
    while (1) {
        sleep(rand() % 3);
        int item = rand() % 100;
        sem_wait(&empty);
        sem_wait(&mutex);
        buffer[in] = item;
        in = (in + 1) % BUFFER_SIZE;
        printf("Produced: %d\n", item);
        sem_post(&mutex);
        sem_post(&full);
    }
    return NULL;
}

void* consumer(void* arg) {
    while (1) {
        sleep(rand() % 3);
        sem_wait(&full);
        sem_wait(&mutex);
        int item = buffer[out];
        out = (out + 1) % BUFFER_SIZE;
        printf("Consumed: %d\n", item);
        sem_post(&mutex);
        sem_post(&empty);
    }
    return NULL;
}

int main() {
    pthread_t producer_thread, consumer_thread;

    sem_init(&empty, 0, BUFFER_SIZE);
    sem_init(&full, 0, 0);
    sem_init(&mutex, 0, 1);

    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);
    sem_destroy(&mutex);

    return 0;
}

OUTPUT:

braham@braham:~/Desktop/program$ gcc prg3.c -o prg3
braham@braham:~/Desktop/program$ ./prg3
Produced: 77
Consumed: 77
Produced: 35
Consumed: 35
Produced: 49
Consumed: 49
Produced: 27
Consumed: 27
Produced: 63
Consumed: 63
Produced: 26
Consumed: 26
Produced: 11
Consumed: 11
Produced: 29
Consumed: 29
Produced: 62
Consumed: 62
Produced: 35
Consumed: 35
Produced: 22

Leave a Reply

Your email address will not be published. Required fields are marked *