Monday, December 21, 2009

Producer Consumer Problem

/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// A Producer Consumer Problem
// Message Queue with single producer and single consumer
// Try the same program without using locks
// Date : 26 - July -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <pthread.h>
#include <queue>
#include <stdio.h>
#include <unistd.h>
#define MAX_SIZE 100000

using namespace std;
pthread_cond_t condition;
pthread_mutex_t my_mutex;

queue <int> cb;

void *ProducerFunc(void *x)
{
// Insert some elements into the buffer.
printf("Producer Threadn");

int i;
for (i=0;i<MAX_SIZE;i++)
{
//printf("inside for loop Producer Threadn");
pthread_mutex_lock(&my_mutex);
cb.push(i);

pthread_cond_signal(&condition);
pthread_mutex_unlock(&my_mutex);
}
pthread_exit(NULL);

}

void *ConsumerFunc(void *x)
{
printf("Consumer Threadn");
int i;
while(1)
{
pthread_mutex_lock(&my_mutex);
pthread_cond_wait(&condition, &my_mutex);

while(!cb.empty())
{
printf("Deleted value is = %dn",cb.front());
cb.pop();
}
pthread_mutex_unlock(&my_mutex);
}

pthread_exit(NULL);
}


int main()
{
pthread_t producer, consumer;
pthread_cond_init(&condition, NULL);
pthread_mutex_init(&my_mutex, NULL);

int rc1 = pthread_create(&producer, NULL, ProducerFunc, NULL);
int rc2 = pthread_create(&consumer, NULL, ConsumerFunc, NULL);
if (rc1 || rc2)
{
printf("ERROR; return code from pthread_create() is %dn", rc1);
return 0;
}
pthread_join(producer, NULL);
pthread_join(consumer, NULL);


pthread_mutex_destroy(&my_mutex);
pthread_cond_destroy(&condition);
pthread_exit(NULL);

return 0;
}

No comments:

Post a Comment