Home » NO IDEA » Producer Consumer Problem

Producer Consumer Problem

Blog Stats

  • 14,863 hits
April 2013
M T W T F S S
« Mar   Oct »
1234567
891011121314
15161718192021
22232425262728
2930  

#include
#include
#include
#include
#define NBUFF 10
int nitems;
struct {
int buff[NBUFF];
sem_t mutex, nempty, nstored;
} shared;
void *produce (void *);
void *consume (void *);
int main(int argc, char **argv)
{
pthread_t tid_produce, tid_consume;
if(argc !=2)
{
printf("Useage: filename ");
return 0;
}
printf ("\n\n Producer - Consumer Problem using Semaphore\n");
printf (" -------------------------------------------\n\n");
nitems=atoi(argv[1]);
sem_init(&shared.mutex,0,1);
sem_init(&shared.nempty,0,NBUFF);
sem_init(&shared.nstored,0,0);
pthread_setconcurrency(2);
pthread_create(&tid_produce,NULL,produce,NULL);
pthread_create(&tid_consume,NULL,consume,NULL);
pthread_join(tid_produce,NULL);
pthread_join(tid_consume,NULL);

sem_destroy(&shared.mutex);
sem_destroy(&shared.nempty);
sem_destroy(&shared.nstored);
return 0;
}
void *produce (void *arg)
{
int i;
for(i=0;i<nitems;i++)
{
sem_wait(&shared.nempty);
sem_wait(&shared.mutex);
shared.buff[i % NBUFF]=i;
printf ("\tProducer.....");
printf ("buff[%d] = %d\n\n",i,shared.buff[i % NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nstored);
sleep(3);
}
return NULL;
}
void *consume (void *arg)
{
int i;
for(i=0;i<nitems;i++)
{
sem_wait(&shared.nstored);
sem_wait(&shared.mutex);
printf("\tConsumer.....");
printf("buff[%d] = %d\n\n\n",i,shared.buff[i%NBUFF]);
sem_post(&shared.mutex);
sem_post(&shared.nempty);

sleep(3);
}
return NULL;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: