first

Tuesday, 31 October 2017

PRODUCER CONSUMER PROBLEM IN C using semaphore and Thread

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

int buf[10];
sem_t mutex,full,empty;



void* producer()
{
    int i;
    for(i=0;i<10;i++)
    {
       
       
   
        sem_wait(&empty);
        sem_wait(&mutex);
        buf[i]=i;
        printf("\nProduced : %d",i);
        sem_post(&mutex);
        sem_post(&full);
        sleep(1);
    }
    pthread_exit("prodused");
}
void* consumer()
{
    int j;
    for(j=0;j<10;j++)
    {
       
        sem_wait(&full);
       
        sem_wait(&mutex);
        printf("\nconsuming item: %d\n",buf[j]);
        sem_post(&mutex);
        sem_post(&empty);
        sleep(6);
    }
    pthread_exit("consumed");
}
void main()
{
    pthread_t t1,t2;

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

    pthread_create(&t1,NULL,producer,NULL);
    pthread_create(&t2,NULL,consumer,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
}



No comments:

Post a Comment

Round Robin Scheduling program in C | Round Robin scheduling Algorithm with Gantt chart c program|scheduling algorithms

/*Copy right SHYAM REGHU $$http://shyamtr.blogspot.in/*/ #include<stdio.h> int at[100],bt[100],rt[100],temp[100]; float wait_time=0,...