Wednesday 19 October 2016

Producer - consumer problem implementation in Linux


Producer consumer problem is one of the very familiar synchronisation issue to be solved by any RTOS.

The following code simulates the producer consumer problem in Linux environment which involves a producer thread generating random values () at particular rate.

The consumer thread utilises the values generated by producer at a certain rate.

Since the producer sleeps for long time and consumer sleeps for less time, the produced data are not consumed in sequence.


#include <pthread.h>
#include <stdlib.h>
#include<stdio.h>
#define N 20
int buffer[N];
void *producer(void *thread_args)
{
     int j,x;
while(1){
     for (j=0;j<N;j++)
     {
           //printf("am producer\n");
           buffer[j]=j+10;
           printf("produced : buffer[%d]=%d\n",j,buffer[j]);
           for(x=0;x<500000000;x++);
     }
     return NULL;
}
}
void *consumer(void *thread_args)
{
     int i,y,value;
     for(i=0;i<N;i++)
     {
           //printf("am in main thread\n");
           value=buffer[i];
           printf("consumed : buffer[%d]=%d\n",i,value);
           for(y=0;y<800000000;y++);
     }
     return NULL;
}

int main()
{
     int i=0,y,value;
     pthread_t tcb1,tcb2;
     if (pthread_create( &tcb1, NULL, producer, NULL))
     {
           printf("error1\n");
           return -1;
     }
     if (pthread_create( &tcb2, NULL, consumer, NULL))
     {
           printf("error2\n");
           return -1;
     }
     pthread_join(tcb1, NULL);
     pthread_join(tcb2, NULL);
     return 1;
}


 The above code (tth.c) can be compiled and executed as follows:
             gcc tth.c tth.o –lpthread
             ./tth

Working of above code is as below:

No comments:

Post a Comment