Producer Consumer C- source code

, by Engineer's Vision

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

pthread_mutex_t mutex;
sem_t full,empty;

int buffer[5],cnt=0;

void *producer(void *);
void *consumer(void *);


int main()
{
    int pno,cno,i;

    printf("\nEnter the producer to be created:");
    scanf("%d",&pno);

    printf("\nEnter no of consumer to be created");
    scanf("%d",&cno);

    pthread_t p[pno],c[cno];

    sem_init(&full,0,0);
    sem_init(&empty,0,5);

    for(i=0;i<pno;i++)
    {
        pthread_create(&p[i],NULL,producer,(void *)i);
        sleep(2);
    }

    for(i=0;i<pno;i++)
    {
        pthread_create(&c[i],NULL,consumer,(void *)i);
        sleep(2);
    }
   
    sem_destroy(&empty);
    sem_destroy(&full);
    printf("\n");
}


void * producer(void * no)
{
    printf("\n Producer %d started ",(int)no);
    int i=rand();
   
    sem_wait(&empty);
    pthread_mutex_lock(&mutex);

    if(cnt<5)
    {
        buffer[cnt++]=1;
        printf("\n Producer %d produced item %d",(int)no,i);
    }

    else
        printf("\nBuffer is full wait....");

    pthread_mutex_unlock(&mutex);
    sem_post(&full);
}


void * consumer(void * no)
{
    int i=(int)no;
    printf("\n\tConsumer %d started",i);

    sem_wait(&full);
    pthread_mutex_lock(&mutex);

    if(cnt>0)
        printf("Consumer %d consumed data %d",i,buffer[cnt--]);
    else
        printf("\n Buffer not empty pl wait for some time..");
    pthread_mutex_unlock(&mutex);
    sem_post(&empty);
}

0 comments: