*Forgive the double post (in Computer Science thread too. As soon as I figure out which thread this should be in, I will be sure to consolidate and delete one.*

I got this example in a handout in class, but am having trouble following...can someone kindly insert some comments? After the problem description, I will make sure I put in what I think is going on, but no guarantees; I missed the lecture on semaphores.

A single-lane bridge connects the two Vermont villages of North Tunbridge and South Tunbridge. Farmers in the two villages use this bridge to deliver their produce to the neighboring town. The bridge can become deadlocked if both a northbound and a southbound farmer get on the bridge at the same time (Vermont farmers are stubborn and are unable to back up).

Forgive the caps cruise-control, but I wanted to differentiate my comments from the code.

monitor bridge
{
  int num_waiting_north = 0, num_waiting_south = 0, on_bridge = 0;
  condition ok_to_cross;
  int prev = 0;

  void enter_bridge_north()
  {
    num_waiting_north++; //DOES THIS MEAN NORTH IS CROSSING?
    while (on_bridge || (prev == 0 && num_waiting_south > 0))
      ok_to_cross.wait(); //PREVENTING THE OTHER SIDE FROM CROSSING, BUT ALLOWING MORE NORTH CROSSING?
    num_waiting_north--;//FINISHED CROSSING?
    prev = 0; //NO IDEA
  }

  void exit_bridge_north()
  {
    on_bridge = 0;
    ok_to_cross.broadcast();
  }

  void enter_bridge_south()
  {
    num_waiting_south++;
    while (on_bridge || (prev == 0 && num_waiting_north > 0))
      ok_to_cross.wait();
    num_waiting_south--;
    prev = 1;
  }
  
  void exit_bridge_south()
  {
    on_bridge = 0;
    ok_to_cross.broadcast();
  }

}

This is what I guess it means

prev==0 means: Last entry to the bridge was from the NORTH
prev==1 means: from SOUTH

void enter_bridge_north()
  {
    num_waiting_north++; //add yourself to the waiting queue
    while (on_bridge || (prev == 0 && num_waiting_south > 0))
/*
*if someone on bridge
*OR
*previous entry was from NORTH and there are people 
*on the SOUTH waiting
*/
      ok_to_cross.wait(); //just wait till the above condition is true
    num_waiting_north--;//Enter the bridge. U r no more waiting, but not finished crossing
    prev = 0; //previous use was from NORTH
  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.