I have a producer consumer C program I am supposed to use
I have a producer & consumer C program .. I am supposed to use threads and metaphores(not Mutex) is in Unix : i have 3 arrays a: 0-19 b: 1-20 C : [20] elements all initilized to zero ..
i\'m supposed to create 3 threads 2 producers and 1 consumer ! the producer reads the value of a & b and sums them in C and updates global sum variable .
this is supposed to be the output :
Output from a sample run can be Producer 1 has written c[0] and updated global sun. Nunber of itens available for consuner: 1. Producer 2 has written c[1] and updated global sun. Number of itens available for consumer: 2. Consuner 1 has read c[0] 1 Consumer 1 has read global summ4 Nunber of itens available for consumer 1 Producer has written c[21 and updated guobau sun. Number of itens available for consumer: 2. Consumer 1 has read c 1] 3 Consuner 1 has read global suna9 Nunber of itens available for consuner: 1. Producer 1 has written c[3] and updated global sun. Nunber of itens available for consuner: 2. Consuner 1 has read c[2] 5 Consuner 1 has read global sun 16 Number of items avatlable for consumer 1.Solution
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum =0;
pthread_mutex_t queue_lock;
int produced;
int c[20] = {0};
int main(int argc, char* argv[])
{
int a[20];
int b[21];
pthread_t P1,P2, C;
pthread_create(&P1,NULL,Produce,&a);
pthread_create(&P2,NULL,Produce,&b);
pthread_create(&C,NULL,Consume,&c);
}
Produce(void* args)
{int in = 0;
int produce =1;
pthread_mutex_lock(&queue_lock);
printf(\"Producer%d has written c[%d] and updated global sum\",produce,in);
printf(\"Number of items available for consumer :%d\",produce);
in++;
produce++;
sum+=sum;
pthread_mutex_unlock(&queue_lock);
}
Consume()
{
int out =0;
int consume = 1;
printf(\"Consumer %d has read c[%d]=%d\",consume,out,consume);
printf(\"Consumer %d has read global sum %d\",consume,sum);
printf(\"Number of items available for consumer:%d\",consume);
}
![I have a producer & consumer C program .. I am supposed to use threads and metaphores(not Mutex) is in Unix : i have 3 arrays a: 0-19 b: 1-20 C : [20] eleme I have a producer & consumer C program .. I am supposed to use threads and metaphores(not Mutex) is in Unix : i have 3 arrays a: 0-19 b: 1-20 C : [20] eleme](/WebImages/36/i-have-a-producer-consumer-c-program-i-am-supposed-to-use-1108481-1761587193-0.webp)
![I have a producer & consumer C program .. I am supposed to use threads and metaphores(not Mutex) is in Unix : i have 3 arrays a: 0-19 b: 1-20 C : [20] eleme I have a producer & consumer C program .. I am supposed to use threads and metaphores(not Mutex) is in Unix : i have 3 arrays a: 0-19 b: 1-20 C : [20] eleme](/WebImages/36/i-have-a-producer-consumer-c-program-i-am-supposed-to-use-1108481-1761587193-1.webp)