Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a multi-threaded C/C++ program that simulates a producer-consumer problem.

ID: 3530103 • Letter: W

Question

Write a multi-threaded C/C++ program that simulates a producer-consumer problem. In the system, there are two producers and three consumers. A common buffer with 5 slots is shared by the producers and consumers. The buffer acts as a circular queue, where an integer is inserted at the tail of the queue and an integer is removed from the head. So you need a head index pointing to the head of the queue and a tail index pointing to the tail of the queue. Use random number generators to generate random delay for the activities of the producers and consumers. A producer produces an integer and insert it into the circular queue and a consumer removes an integer from the queue. If a consumer finds that the shared buffer is empty, it puts itself in a consumer-waiting-queue and goes to sleep, which will be woken up by a producer. On the other hand if a producer finds the shared buffer full, it puts itself in a producer-waiting-queue and goes to sleep.

Explanation / Answer

# include # include # define BufferSize 10 void *Producer(); void *Consumer(); int BufferIndex=0; char *BUFFER; pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER; pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER; pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER; int main() { pthread_t ptid,ctid; BUFFER=(char *) malloc(sizeof(char) * BufferSize); pthread_create(&ptid,NULL,Producer,NULL); pthread_create(&ctid,NULL,Consumer,NULL); pthread_join(ptid,NULL); pthread_join(ctid,NULL); return 0; } void *Producer() { for(;;) { pthread_mutex_lock(&mVar); if(BufferIndex==BufferSize) { pthread_cond_wait(&Buffer_Not_Full,&mVar); } BUFFER[BufferIndex++]='@'; printf("Produce : %d ",BufferIndex); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Empty); } } void *Consumer() { for(;;) { pthread_mutex_lock(&mVar); if(BufferIndex==-1) { pthread_cond_wait(&Buffer_Not_Empty,&mVar); } printf("Consume : %d ",BufferIndex--); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Full); } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote