Thursday, August 15, 2013

Bathroom problem

There is a single bathroom in a hostel, which is shared by boys and girls. Following rules are applicable -
  • Any number of males can enter the bathroom, if there is a male inside it.
  • Any number of females can enter the bathroom, if there is a female inside it.
  • Male or female will wait in a queue if any opposite sex is inside the bathroom.
  • Everybody gets to use the bathroom in fair way and there is no starvation.
Code that provides no fairness
Bathroom.java
Test.java

Solution

There are different way to approach a problem and in that one approach is to solve a simpler version of problem and then build over a bigger solution.  lets try to break this problem. If problem is that only one man or female can enter in a bathroom then we have created one bathroom lock and every body was waiting on that if it was acquire by any other thread. but this problem states that multiple threads of same type can enter in bathroom. That's mean ,  different types of threads cannot wait on same lock. we need more locks on which thread can wait. so we need three locks.

 Semaphore bathroom = new Semaphore(1);
 Semaphore mutexForMan = new Semaphore(1);
 Semaphore mutexforWomen = new Semaphore(1);

We also need a variable by which we can identify that who is using bathroom so that other type of thread can wait and same type of thread can processed.


       public void manEnter() throws Exception
{
mutexForMan.acquire();
numberOfMan++;
if (numberOfMan == 1)
{
bathroom.acquire(); // used to control entry in  bathroom
System.out.println("Man acquire room" );
}
System.out.println("Number of Mans=" + numberOfMan);
mutexForMan.release();
}

public void manExit() throws Exception
{
mutexForMan.acquire();
numberOfMan--;
if (numberOfMan == 0)
{
System.out.println("Man release room" );
bathroom.release();

}
mutexForMan.release();
}

public void womanEnter() throws Exception
{
mutexforWomen.acquire();
numberOfWoman++;
if (numberOfWoman == 1)
{
bathroom.acquire();
System.out.println("Woman acquire room" );
}
System.out.println("Number of Woman=" + numberOfWoman);
mutexforWomen.release();
}

public void womenExit() throws Exception
{
mutexforWomen.acquire();
numberOfWoman--;
if (numberOfWoman == 0)
{
System.out.println("Woman release room" );
bathroom.release();

}
mutexforWomen.release();
}




No comments:

Post a Comment