Information Technology Reference
In-Depth Information
voidBarberShop::barberDay()
{
boolBarberShop::getHairCut()
{
//BarberDayisnotanatomicaction.
//Nolock.Onlytouchobject'sstate
//bycallingmethodsthatlock.
intcust;
printf("Openingfortheday\n");
openStore();
while(1){
cust=waitForCustomer();
if(cust==NO_CUST_CLOSING_TIME){
printf("Closingfortheday\n");
printFinalStats();
return;
intmyNumber;
boolret;
lock.Acquire();
if(!open||waitingRoomFull()){
ret=false;
}
else{
//"Takeanumber"toensureFIFOservice
myNumber=++arrivalCount;
wakeBarber.Signal(&lock);
while(stillNeedHaircut(myNumber)){
nextCustomer.Wait(&lock);
}
printf("Cuthair%d\n",cust);
sthread_sleep(1,0); //Simulatetimetocut
doneCutting();
}
ret=true;
}
lock.Release();
returnret;
}
}
}
voidBarberShop::openStore()
{
voidBarberShop::clockRingsClosingTime()
{
lock.Acquire();
open=true;
lock.Release();
return;
lock.Acquire();
timeToClose=true;
wakeBarber.Signal(&lock);
lock.Release();
}
}
intBarberShop::waitForCustomer()
{
//Internalfunctionsforcheckingstatus.
// Alwayscalledwithlockalreadyheld.
boolBarberShop::emptyAndOpen()
{
intcustId;
lock.Acquire();
while(emptyAndOpen()){
wakeBarber.Wait(&lock);
if((timeToClose||(arrivalCount>cutCount))){
returnfalse;
}
if(timeToClose){
open=false; //Stopnewarrivals
}
else{
returntrue;
}
if(arrivalCount>cutCount){
custId=cutCount;
}
}
}
else{
custId=NO_CUST_CLOSING_TIME;
boolBarberShop::stillNeedHaircut(intcustId)
{
//EnsureFIFOorderbylettingcustomers
//leaveinordertheyarrive
if(custId>cutCount){
returntrue;
}
lock.Release();
returncustId;
}
}
else{
returnfalse;
voidBarberShop::doneCutting()
{
}
lock.Acquire();
cutCount++;
nextCustomer.Broadcast(&lock);
lock.Release();
return;
}
boolBarberShop::waitingRoomFull()
{
//+1b/cbarberchair
if(arrivalCount-cutCount==NCHAIRS+1){
returntrue;
}
voidBarberShop::printFinalStats()
{
}
else{
returnfalse;
lock.Acquire();
printf("Stats:arrived=%dcut=%dfull=%d\n",
arrivalCount,cutCount,fullCount);
assert(arrivalCount==cutCount);
lock.Release();
}
}
}
Figure5.17: BarberShop.cc defines our Sleeping Barber solution
 
Search WWH ::




Custom Search