Solution to Cigarette-Smokers Problem

we can have semaphore based pairs of all three supplies as follows

Semaphore tobaccoAndPaper = 0;
Semaphore matchesAndTobacco = 0;
Semaphore paperAndMatches = 0;

and a single semaphore to signal agent that the current smoker is done with smoking and the agent can put other supplies

Semaphore doneSmoking = 1; //binary
void agent(){
do{
wait(doneSmoking);
int r = rand() % 3;
//signal whichever combination is choosen at random
switch®{
case 0: signal( tobaccoAndPaper );
break;
case 1: signal( matchesAndTobacco );
break;
case 2: signal( paperAndMatches );
break;
}
}while(TRUE);
}
//code for smoker would be
void smoker_P(){//smoker with paper
while(TRUE){
//wait for the two ingredients
wait(matchesAndTobacco);
smoke();
signal( doneSmoking );
}
}

code of smoker_T() and smoker_M() is similar.

  • agent is waiting for a single smoker to be done with smoking which has nothing to do with agent’s work, think of the OS-processes analogy related to the problem where agent is the OS and smokers are the processes.
  • we are deliberately putting hold and wait to end by making the smoker wait for exact combination he/she needs to smoke, which has its own consequences like process has to wait for too long considering real system.
  • we are selecting the pair at random which results in unequal chance of smoking to the smokers
    source

This looks like a reasonably good solution! Nice work :slight_smile:

1 Like

not my work though, added source now. bhaiya what about the no hold and wait condition?, I also read about the use of pusherFunction by agent which is even better.