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

Making use of Semaphores and Pthreads, create a program in C to handle the follo

ID: 3592350 • Letter: M

Question

Making use of Semaphores and Pthreads, create a program in C to handle the following.

You are asked to implement 4 (four) threads that we call "providers" and a simple-main-program for 260 (two-hundred and sixty) threads that we call "buyers". The providers' threads produce different integer-numbers and put them in a queue. Design and implement a program that will handle the synchronization of providers' threads as well as buyers' threads. Basically the program should make sure that only one provider inserts items (integer representing number of items) and prints it on the screen. The other provider threads should sleep for some time while the thread buyer is buying. When a thread wakes up, it tries to by an integer from the queue. Make sure that each and all buyers get a chance to buy an item, represented by a number. No buyer should make the other ones starve. The provider should not stop providing items (i.e. numbers representing items). Make sure that each and all of the providers get a chance to insert items (i.e. numbers). Hint: You can use a minimum of 10 buffers.

Explanation / Answer

C Program implementing the Use Case:

#include<stdio.h>

#include<time.h>

#include<semaphore.h>

#include<pthread.h>

#include<stdlib.h>

#define buffersize 10

#define NUM_PROVIDER 4

#define NUM_BUYER 260

pthread_mutex_t mutex;

pthread_t tidP[NUM_PROVIDER],tidB[NUM_BUYER];

sem_t full,empty;

int counter;

int buffer[buffersize];

void initialize()

{

pthread_mutex_init(&mutex,NULL);

sem_init(&full,1,0);

sem_init(&empty,1,buffersize);

counter=0;

}

void write(int item)

{

buffer[counter++]=item;

}

int read()

{

return(buffer[--counter]);

}

void * provider (void * param)

{

int waittime,item,i;

srand(time(NULL));

item=rand()%5000;

waittime=rand()%5;

sem_wait(&empty);

pthread_mutex_lock(&mutex);

printf(" Provider has added item: %d ",item);

write(item);

pthread_mutex_unlock(&mutex);

sem_post(&full);

}

void * buyer (void * param)

{

int waittime,item;

waittime=rand()%5;

sem_wait(&full);

pthread_mutex_lock(&mutex);

item=read();

printf(" Buyer has bought item: %d ",item);

pthread_mutex_unlock(&mutex);

sem_post(&empty);

}

int main()

{

int i;

initialize();

for(i=0;i<NUM_PROVIDER;i++)

pthread_create(&tidP[i],NULL,provider,NULL);

for(i=0;i<NUM_BUYER;i++)

pthread_create(&tidB[i],NULL,buyer,NULL);

for(i=0;i<NUM_PROVIDER;i++)

pthread_join(tidP[i],NULL);

for(i=0;i<NUM_BUYER;i++)

pthread_join(tidB[i],NULL);

return 0;

}

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