Академический Документы
Профессиональный Документы
Культура Документы
Your barber is a lazy man and wants to sleep when he/she is not working. At the same time
he/she does not want to lose customers. So he/she buys N seats to his/her barbershop. If all
seats are empty your barber sleeps until a customer came. If a customer come to barbershop and
there is no seats available, customer leaves the barbershop and goes other one on the street.
SOLUTION
#include <Windows.h>
#include <stdio.h>
#include <time.h>
#define NUMBER_OF_CUSTOMERS 6
#define NUMBER_OF_SEATS 5
#define NUMBER_OF_BARBERS 1
void cutHair();
mutex=CreateSemaphore(NULL,1,1,NULL);
customerSemaphore = CreateSemaphore(NULL, 0, 1, NULL);
barberSemaphore = CreateSemaphore(NULL, 0, 1, NULL);
HANDLE threadCus[NUMBER_OF_CUSTOMERS];
HANDLE threadBar;
DWORD cusThreadId;
DWORD barThreadId;
for(int i=0;i<NUMBER_OF_CUSTOMERS;++i) {
threadCus[i] = CreateThread(NULL, 0, customer, (LPVOID)i, 0,
&cusThreadId);
}
threadBar = CreateThread(NULL, 0, barber, (LPVOID)1, 0,
&barThreadId);
WaitForMultipleObjects(NUMBER_OF_CUSTOMERS,threadCus,TRUE,INFINITE);
WaitForSingleObject(threadBar,INFINITE);
if(NumberFreeSeats == NUMBER_OF_SEATS)
{
printf("Sleeping \n"); //if no customer,sleep
Sleep(sleep);
}
else
{
NumberFreeSeats++; //else work & increase number of free
chairs
WaitForSingleObject(mutex,INFINITE); // only one person
on barber chair
cutHair();
ReleaseSemaphore(mutex,1,NULL);
ReleaseSemaphore(barberSemaphore,1,NULL);// barber is ready
to cut
Sleep(sleep);
}
while(TRUE)
{
DWORD sleep = rand()%2001;
}
else
{
printf("No Empty Seats - Customer Leaves. \n");
}
Sleep(sleep);
}
void cutHair() {
DWORD sleep = rand()%2001;
printf("Barber is cutting customer's hair. \n");
Sleep(sleep);
}
By H.Ö