In: Computer Science
A snooker club can be used by players of both sex i.e. male and female, but not both at the same time. If a boy is in the club, other boys may enter, but any girl wishing to play snooker should wait until all boys leave and club become empty. Similarly, if a girl is in the club, other girls may enter, but any boy wishing to play should wait till the club becomes empty. Implement a solution to this problem using SEMAPHORES. At maximum only 6 boys or 6 girls can enter the club and play snooker as there are only 3 tables available in the club.
Male Snooker:
do{
// Male snooker want to
enter into club so wait on m_snook
// bcoz we are changing
common variable n_m_snook(no of male snooker)
wait(m_snook);
//incrementing no of
male snookers
n_m_snook++;
//blocking the female
snookers if he is the first male snooker to enter into club
if(n_m_snook==1)
{
wait(f_snook);
}
//blocking the male
snooker if n_m_snook>6
//since we can allow
only 6 snookers
if(n_m_snook>6)
{
//blocking male snooker until one male snooker left the club
while(n_m_snook>6)
{
wait(m_snook);
}
}
//now the male snooker
entered into club
//now we can allow other
male snookers
//so signal on
m_snoock
signal(m_snook);
//one male snooker want
to leave the club and change the n_m_snook
//Therefore wait on
m_snook
wait(m_snook);
//decrement the
n_m_snook value
n_m_snook--;
//if he is the last male
snooker to leave the club
//then we can allow
female snookers to the club
if(n_m_snook==0)
{
signal(f_snook);
}
//male snooker changed
n_m_snook value and left
signal(m_snook);
}while(true);
Female Snooker:
do{
// female snooker want
to enter into club so wait on f_snook
// bcoz we are changing
common variable n_f_snook(no of male snooker)
wait(f_snook);
//incrementing no of
female snookers
n_f_snook++;
//blocking the male
snookers if she is the first female snooker to enter into
club
if(n_f_snook==1)
{
wait(m_snook);
}
//blocking the female
snooker if n_f_snook>6
//since we can allow
only 6 snookers
if(n_f_snook>6)
{
//blocking female snooker until one female snooker left the
club
while(n_f_snook>6)
{
wait(f_snook);
}
}
//now the female snooker
entered into club
//now we can allow other
female snookers
//so signal on
f_snoock
signal(f_snook);
//one female snooker
want to leave the club and change the n_f_snook
//Therefore wait on
f_snook
wait(f_snook);
//decrement the
n_f_snook value
n_f_snook--;
//if she is the last
female snooker to leave the club
//then we can allow male
snookers to the club
if(n_f_snook==0)
{
signal(m_snook);
}
//female snooker changed
n_f_snook value and left
signal(f_snook);
}while(true);
semaphores used: m_snook, f_snook
common variables used: n_m_snook, n_f_snook
wait()--decrements the value by 1(makes 0 )
signal()--increments the value by 1