(Homework Solution): Task 5: Implement semaphores (30 marks) Copy your code from Task 4 into a new directory

Task 5: Implement semaphores (30 marks) Copy your code from Task 4 into a new directory named task5.
Stage 1 Replace the use of busy waiting with semaphores to achieve mutual exclusion and synchronise message passing between the producer and consumer. As with Task 1, you will need to research the Linux system calls necessary to accomplish this. The semget function is a good starting point.

• Your producer should now initially sleep for 1 second (1000 ms) between writing messages.
• Continue adjusting the sleep interval based on the message content as described in Task 4.
• Sleep intervals less than 800 ms are now valid. A value of 0 ms indicates the producer should not sleep between writing messages to the shared memory segment.

You will need to consider how the consumer can be configured to only read a message when it is ready and how the producer can be configured to not overwrite a message before the consumer has had chance to read it.

Stage 2 As before, use top to observe the utilisation of the producer and consumer for a variety of producer sleep intervals (as controlled by the message content).

Does the implementation of semaphores make a difference to utilisation?
Discuss your observations in your report and compare with previous tasks’ results.

Hint: Think about how many semaphores you would need to achieve mutual exclusion and synchronisation between the producer and consumer. Refer back to the concurrency lecture material from week 4 if you need to refresh your memory on these concepts.

#task 4 code

#define _REENTRANT

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include <pthread.h>
#include <semaphore.h>

// The maximum number of customer threads.
#define MAX_CUSTOMERS 25

// Function prototypes…
void *customer(void *num);
void *barber(void *);

void randwait(int secs);

// Define the semaphores.

// waitingRoom Limits the # of customers allowed
// to enter the waiting room at one time.
sem_t waitingRoom;

// barberChair ensures mutually exclusive access to
// the barber chair.
sem_t barberChair;

// barberPillow is used to allow the barber to sleep
// until a customer arrives.
sem_t barberPillow;

// seatBelt is used to make the customer to wait until
// the barber is done cutting his/her hair.
sem_t seatBelt;

// Flag to stop the barber thread when all customers
// have been serviced.
int allDone = 0;

int main(int argc, char *argv[]) {
pthread_t btid;
pthread_t tid[MAX_CUSTOMERS];
long RandSeed;
int i, numCustomers, numChairs;
int Number[MAX_CUSTOMERS];

// Check to make sure there are the right number of
// command line arguments.
if (argc != 4) {
printf(“Use: SleepBarber <Num Customers> <Num Chairs> <rand seed>n”);
exit(-1);
}

// Get the command line arguments and convert them
// into integers.
numCustomers = atoi(argv[1]);
numChairs = atoi(argv[2]);
RandSeed = atol(argv[3]);

// Make sure the number of threads is less than the number of
// customers we can support.
if (numCustomers > MAX_CUSTOMERS) {
printf(“The maximum number of Customers is %d.n”, MAX_CUSTOMERS);
exit(-1);
}

printf(“nSleepBarber.cnn”);
printf(“A solution to the sleeping barber problem using semaphores.n”);

// Initialize the random number generator with a new seed.
srand48(RandSeed);

// Initialize the numbers array.
for (i=0; i<MAX_CUSTOMERS; i++) {
Number[i] = i;
}

// Initialize the semaphores with initial values…
sem_init(&waitingRoom, 0, numChairs);
sem_init(&barberChair, 0, 1);
sem_init(&barberPillow, 0, 0);
sem_init(&seatBelt, 0, 0);

// Create the barber.
pthread_create(&btid, NULL, barber, NULL);

// Create the customers.
for (i=0; i<numCustomers; i++) {
pthread_create(&tid[i], NULL, customer, (void *)&Number[i]);
}

// Join each of the threads to wait for them to finish.
for (i=0; i<numCustomers; i++) {
pthread_join(tid[i],NULL);
}

// When all of the customers are finished, kill the
// barber thread.
allDone = 1;
sem_post(&barberPillow); // Wake the barber so he will exit.
pthread_join(btid,NULL);
}

void *customer(void *number) {
int num = *(int *)number;

// Leave for the shop and take some random amount of
// time to arrive.
printf(“Customer %d leaving for barber shop.n”, num);
randwait(5);
printf(“Customer %d arrived at barber shop.n”, num);

// Wait for space to open up in the waiting room…
sem_wait(&waitingRoom);
printf(“Customer %d entering waiting room.n”, num);

// Wait for the barber chair to become free.
sem_wait(&barberChair);

// The chair is free so give up your spot in the
// waiting room.
sem_post(&waitingRoom);

// Wake up the barber…
printf(“Customer %d waking the barber.n”, num);
sem_post(&barberPillow);

// Wait for the barber to finish cutting your hair.
sem_wait(&seatBelt);

// Give up the chair.
sem_post(&barberChair);
printf(“Customer %d leaving barber shop.n”, num);
}

void *barber(void *junk) {
// While there are still customers to be serviced…
// Our barber is omnicient and can tell if there are
// customers still on the way to his shop.
while (!allDone) {

// Sleep until someone arrives and wakes you..
printf(“The barber is sleepingn”);
sem_wait(&barberPillow);

// Skip this stuff at the end…
if (!allDone) {

// Take a random amount of time to cut the
// customer’s hair.
printf(“The barber is cutting hairn”);
randwait(3);
printf(“The barber has finished cutting hair.n”);

// Release the customer when done cutting…
sem_post(&seatBelt);
}
else {
printf(“The barber is going home for the day.n”);
}
}
}

void randwait(int secs) {
int len;

// Generate a random number…
len = (int) ((drand48() * secs) + 1);
sleep(len);
}

Expert Answer

answers

Please let me know if you have any doubts or you want me to modify the code. And if you find this code useful then don’t forget to rate my answer as thumps up. Thank you! 🙂

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_CUSTOMERS 30

void *customer(void *num);
void *barber(void *);
void rwait(int secs);

sem_t waitingRoom; sem_t barberChair; sem_t barberP; sem_t seatBelt;
int all = 0;
int main(int argc, char *argv[])
{
pthread_t btid;
pthread_t tid[MAX_CUSTOMERS];
int i, x, nCustomers, nChairs; int Number[MAX_CUSTOMERS];
printf(“Enter number of customers and chairs.max=30n”);
scanf(“%d”,&x);
nCustomers = x;
scanf(“%d”,&x);
nChairs = x;
if (nCustomers > MAX_CUSTOMERS) {
printf(“The max Customers is %d.n”, MAX_CUSTOMERS);
system(“PAUSE”);
return 0;
}

for (i = 0; i < MAX_CUSTOMERS; i++) {
Number[i] = i;
}

sem_init(&waitingRoom, 0, nChairs);
sem_init(&barberChair, 0, 1);
sem_init(&barberP, 0, 0);
sem_init(&seatBelt, 0, 0);

pthread_create(&btid, NULL, barber, NULL);

for (i = 0; i < nCustomers; i++) {
pthread_create(&tid[i], NULL, customer, (void *)&Number[i]);
}

for (i = 0; i < nCustomers; i++) {
pthread_join(tid[i],NULL);
}

all = 1;
sem_post(&barberP);
pthread_join(btid,NULL);
system(“PAUSE”);
return 0;
}

void *barber(void *junk)
{

while (!all) {
printf(“The barber is sleepingn”);
sem_wait(&barberP);
if (!all)
{
printf(“The barber is cutting hairn”);
rwait(3);
printf(“The barber has finished cutting hair.n”);
sem_post(&seatBelt);
}
else {
printf(“The barber is done jobn”);
}
}
}
void *customer(void *number) {
int num = *(int *)number;
printf(“Customer %d leaving for barber shop.n”, num);
rwait(5);
printf(“Customer %d arrived at barber shop.n”, num);
sem_wait(&waitingRoom);
printf(“Customer %d entering waiting room.n”, num);
sem_wait(&barberChair);
sem_post(&waitingRoom);
printf(“Customer %d waking the barber.n”, num);
sem_post(&barberP);
sem_wait(&seatBelt);
sem_post(&barberChair);
printf(“Customer %d leaving barber shop.n”, num);
}

void rwait(int secs) {
int len = 1;
sleep(len);
}
Barber /CLionProjects/Barber] ./main.c Barber /Users/swapnil/CLionProjects/Barber/cmake-build-debug/Barber Enter number of customers and chairs.max 38 The barber is sleeping The barber is cutting hair Customer leaving for barber shop Customer 1 leaving for barber shop Customer 5 leaving for barber shop Customer 2 Leaving for barber shop Customer 7 leaving for barber shop Customer 8 leaving for barber shop Customer 3 leaving for barber shop Customer 4 leaving for barber shop Customer 9 leaving for barber shop Customer 6 leaving for barber shop Customer 5 arrived at barber shop Customer 5 entering waiting roon. Customer 1 arrived at barber shop Customer 1 entering waiting roon. Customer 1 waking the barber Customer arrived at barber shop Customer 8 entering waiting roon. Customer 7 arrived at barber shop Customer 8 arrived at barber shop Customer 8 entering waiting roon. Customer 8 waking the barber The barber has finished cutting hair The barber is sleeping The barber is cutting hair Customer 5 waking the barber Customer 1 leaving barber shop. Customer 5 leaving barber shop. Customer 7 entering waiting roon. Customer 7 waking the barber Customer 7 leaving barber shop. Customer 6 arrived at barber shop Customer 6 entering waiting roon. Customer 6 waking the barber Customer waking the barber Customer 3 arrived at barber shop Customer 3 entering waiting roon. Customer 3 waking the barber Customer 4 arrived at barber shop Customer 3 leaving barber shop. Customer 8 leaving barber shop. Customer 2 arrived at barber shop Terminal ㅿ CMake -0: Messages Process finished with exit code 0 Q Event Log Context: Barber [D] 맬 4: 6: T000 64:1 LF: UTF-8수

iWriteHomework
Order NOW for a 10% Discount
Pages (550 words)
Approximate price: -

Why Us?

Top Quality and Well-Researched Papers

All ourbpapers are written from scratch. In fact, Clients who ask for paraphrasing services are highly discouraged. We have writers ready to craft any paper from scratch and deliver quality ahead of time.

Professional and Experienced Academic Writers

Our writers keeps you posted on your papers progress - providing you with paper outline/draft. You are also at liberty to communicate directly with your writer.

Free Unlimited Revisions

If you think we missed something, send your order for a free revision. You have 10 days to submit the order for review after you have received the final document. You can do this yourself after logging into your personal account or by contacting our support.

Prompt Delivery and 100% Money-Back-Guarantee

All papers are always delivered on time, in many cases quite ahead of time. In case we need more time to master your paper, we may contact you regarding the deadline extension. In case you cannot provide us with more time, a 100% refund is guaranteed.

Original & Confidential

We use several writing tools checks to ensure that all documents you receive are free from plagiarism. Our editors carefully review all quotations in the text. We also promise maximum confidentiality in all of our services.

24/7 Customer Support

Our support agents are available 24 hours a day 7 days a week and committed to providing you with the best customer experience. Get in touch whenever you need any assistance.

Try it now!

Calculate the price of your order

Total price:
$0.00

How it works?

Follow these simple steps to get your paper done

Place your order

Fill in the order form and provide all details of your assignment.

Proceed with the payment

Choose the payment system that suits you most.

Receive the final file

Once your paper is ready, we will email it to you.

Our Services

No need to work on your paper at night. Sleep tight, we will cover your back. We offer all kinds of writing services.

Essays

Essay Writing Service

No matter what kind of academic paper you need and how urgent you need it, you are welcome to choose your academic level and the type of your paper at an affordable price. We take care of all your paper needs and give a 24/7 customer care support system.

Admissions

Admission Essays & Business Writing Help

An admission essay is an essay or other written statement by a candidate, often a potential student enrolling in a college, university, or graduate school. You can be rest assurred that through our service we will write the best admission essay for you.

Reviews

Editing Support

Our academic writers and editors make the necessary changes to your paper so that it is polished. We also format your document by correctly quoting the sources and creating reference lists in the formats APA, Harvard, MLA, Chicago / Turabian.

Reviews

Revision Support

If you think your paper could be improved, you can request a review. In this case, your paper will be checked by the writer or assigned to an editor. You can use this option as many times as you see fit. This is free because we want you to be completely satisfied with the service offered.

× Contact Live Agents