Consider the producer-consumer problem where the producer produces items to be consumed by the consumer. A solution of t

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Consider the producer-consumer problem where the producer produces items to be consumed by the consumer. A solution of t

Post by answerhappygod »

Consider the producer-consumer problem where the producer
produces items to be consumed by the consumer. A solution of the
problem is to be implemented using threads. The main process will
run producer and consumer as two different threads. The producer
will put the items it generates into a buffer of length 15. The
consumer reads the elements of the buffer to get the items. A
solution is given below. Each item produced and consumed are also
printed to the screen. Run the program several times and find a
sample run when the items produced are not correctly consumed.
Explain why the program does not always work correctly.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int buffer[15] = {0};
int in =0, out = 0;
void *Producer()//
{
int nextp;
for(int i=0;i<15;i++){
//produce an item
nextp = 2*3+i;
buffer[in] = nextp;
printf("The producer produced the
item = %d\n",nextp);
in = (in+1);
}
}
void *Consumer()//
{
int nextc;
for(int i=0;i<15;i++){
nextc = buffer[out];
printf("The consumer consumed the
item = %d\n",nextc);
out = (out+1);
}
}
void main()
{
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL,
Producer, NULL);
pthread_create(&thread2, NULL,
Consumer, NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
exit(0);
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply