Unisex Bathroom Problem
Explore the Unisex Bathroom Problem to understand how to synchronize multi-threaded access with constraints on gender exclusivity and occupancy limits. Learn to implement state tracking using mutexes and condition variables, and control access with semaphores to avoid deadlocks, providing a practical concurrency solution in Ruby.
We'll cover the following...
Unisex Bathroom Problem
A bathroom is being designed for the use of both males and females in an office but requires the following constraints to be maintained:
- There cannot be men and women in the bathroom at the same time.
- There should never be more than three employees in the bathroom simultaneously.
The solution should avoid deadlocks. For now, though, don’t worry about starvation.
Solution
First let us come up with the skeleton of our Unisex Bathroom class. We want to model the problem programmatically first. We'll need two APIs, one that is called by a male to use the bathroom and another that is called by a female to use the bathroom. Initially, our class looks like the following:
class UnisexBathroomProblem
def initialize()
end
def useBathroom(name)
end
def maleUseBathroom(name)
end
def femaleUseBathroom(name)
end
end
Let us try to address the first problem of allowing either men or women to use the bathroom. We'll worry about the max employees later. We need to maintain state in a variable to track which gender is currently using the bathroom. Let's call this variable inUseBy. The variable inUseBy will take on the values female, male or none to denote the gender currently using the bathroom.
We'll also have a method useBathroom() that'll mock a person using the bathroom. The implementation of this ...