title: Unisex bathroom synchronization
body: <p>I have come up with the following solution for the unisex bathroom synchronization.</p>
  
  <p>The problem has the following constraints:</p>
  
  <ul>
  <li>There is a shared bathroom which has a limited capacity.</li>
  <li>Males and females cannot use the bathroom at the same time</li>
  <li>An individual will spend arbitrary some time using the bathroom</li>
  <li>An individual does not like to wait to use the bathroom (minimize waiting time)</li>
  <li>The solution should not be biased to males or females.</li>
  </ul>
  
  <p>See <a href="http://www.credmond.net/projects/unisex-bathroom-problem/" rel="nofollow">link</a> for a detailed description of the problem.</p>
  
  <p>Does the below mentioned solution satisfy all the problem constraints?</p>
  
  <p><strong>Pseudo code</strong></p>
  
  <pre><code>int female_cnt = 0;
  mutex female_cnt_mutex;
  
  int male_cnt = 0;
  mutex male_cnt_mutex;
  
  mutex female_mutex;
  mutex male_mutex;
  
  semaphore restroom = N;
  
  female()
  {
      lock(female_mutex)
      unlock(female_mutex)
  
      lock(female_cnt_mutex)
  
      female_cnt++;
      if (female_cnt == 1)
          lock(male_mutex)
  
      unlock(female_cnt_mutex)
  
      wait(restroom)
  
      do_stuff();
  
      signal(restroom)
  
      lock(female_cnt_mutex)
  
      female_cnt--;
      if (female_cnt == 0)
          unlock(male_mutex)
  
      unlock(female_cnt_mutex)
  }
  
  male()
  {
      lock(male_mutex)
      unlock(male_mutex)
  
      lock(male_cnt_mutex)
  
      male_cnt++;
      if (male_cnt == 1)
          lock(female_mutex)
  
      unlock(male_cnt_mutex)
  
      wait(restroom)
  
      do_stuff();
  
      signal(restroom)
  
      lock(male_cnt_mutex)
  
      male_cnt--;
      if (male_cnt == 0)
          unlock(female_mutex)
  
      unlock(male_cnt_mutex)
  }
  </code></pre>