14.1 Traffic light example

Below we show an example of a traffic light that alternates between red and green in direction north and south respectively.

trafficSystem: obj
   class TrafficLight(direction: ref String):
      state: ref String
      cycle
         state:= "red"
         this(TrafficLight).suspend
         state:= "green"
         this(TrafficLight).suspend
   north: obj TrafficLight("North:")
   south: obj TrafficLight("South:")
   north.call -- set north to green
   cycle
      north.call
      south.call
      sleep(1000)

The object trafficSystem has a class TrafficLight, which represents the concept of a traffic light.

Two objects north and south of type TrafficLight are declared (and thereby generated). The generation of a TrafficLight-object implies that the statements in the class are executed. This means execution of cycle ... This has the effect that the variable state is assigned the string "red".

Then the statement this(TrafficLight).suspend is executed. This has the effect that execution of the TrafficLight-object is temporarily suspended. The effect is that after the declarations of north and south, they both have state = "red".

Immediately after the generation of north and south the trafficSystemexecutes north.call. This has the effect that execution of north is resumed, which implies execution of state := "green" followed by a new suspension of the execution of north.

The situation is then that north.state = "green" and south.state = "red".

The TrafficSystem then executes a cycle where north and south both are resumed implying that their state variables swithces from "green" to "red"of "red" to "green" and so on. The TrafficSystem then sleeps for some time before another iteration in the cycle.