montimaj

Producer-Consumer

Sep 29th, 2015
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<omp.h>
  3. #define MAX 10
  4. void produce(int *q,int *rear,int *count)
  5. {
  6.         int x=0;
  7.         while(1)
  8.         {
  9.             if(*count<MAX)
  10.             {
  11.                 *rear=(*rear+1)%MAX;
  12.                 q[*rear]=++x;
  13.                 printf("Producer produced %d\n",x);
  14.                 (*count)++;
  15.             }
  16.             else
  17.                 printf("Buffer full\n");
  18.             fgetc(stdin);          
  19.         }
  20. }
  21. void consume(int *q,int *front,int *count)
  22. {
  23.         while(1)
  24.         {
  25.             if(*count)
  26.             {
  27.                 printf("Consumer consumed %d\n",q[*front]);
  28.                 *front=(*front+1)%MAX;
  29.                 (*count)--;
  30.             }
  31.             else
  32.                 printf("Buffer empty!\n");
  33.             fgetc(stdin);
  34.         }      
  35. }
  36. int main()
  37. {
  38.     omp_set_dynamic(0);
  39.     int q[MAX],rear=-1,front=0,count=0;
  40.     #pragma omp parallel num_threads(2)
  41.     if(!omp_get_thread_num())
  42.         produce(q,&rear,&count);
  43.     else
  44.         consume(q,&front,&count);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment