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

Implement the Producer-Consumer Problem in C Implement the Producer-Consumer Pro

ID: 3676055 • Letter: I

Question

Implement the Producer-Consumer Problem in C

Implement the Producer-Consumer Problem: Use processes to simulate producers and consumers, and let all of them share a buffer with size 10. The buffer contains random capital letters 'A' - 'Z' In the simulation scenario, set 2 producers and 2 consumers, let each of them access and change the buffer for 5 times in random time intervals. Use semaphore for process synchronization. Output the process execution sequence, and the buffer every time a producer or consumer changes it.

Explanation / Answer

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>
#include<unistd.h>
#include <stdlib.h>

void* producer(void *arg);
void* consumer(void *arg);
char cArray[10]={'a','b','c','d','e','f','g','h','i','z'};
char buff[10];

sem_t produced,consumed;

int main()
{
pthread_t pid1,cid1,pid2,cid2;

sem_init(&consumed,0,1);
sem_init(&produced,0,0);

pthread_create(&pid1,NULL,producer,NULL);
sleep(rand() % 10);
pthread_create(&cid1,NULL,consumer,NULL);
sleep(rand() % 10);
pthread_create(&pid2,NULL,producer,NULL);
sleep(rand() % 10);
pthread_create(&cid2,NULL,consumer,NULL);

pthread_join(pid1,NULL);
pthread_join(cid1,NULL);
pthread_join(pid2,NULL);
pthread_join(cid2,NULL);
}

void* producer(void*arg)
{
sem_wait(&consumed);
strcpy(buff,cArray);
sem_post(&produced);
return NULL;
}

void* consumer(void *arg)
{
sem_wait(&produced);
printf("recieved %s ",buff);
sem_post(&consumed);
return NULL;
}