Parallele_Verteilte_Systeme/go/TrafficLights/TrafficLight.go

98 lines
2.1 KiB
Go

package main
import (
"fmt"
)
var debuggingAllowed = true
type CardinalDirection string
const (
north = CardinalDirection("North")
south = CardinalDirection("South")
east = CardinalDirection("East")
west = CardinalDirection("West")
)
var Directions = []CardinalDirection{
north, south, east, west,
}
type Colour string
const (
red = Colour("\u001B[31m Red \u001B[0m")
green = Colour("\u001B[33m Green \u001B[0m")
yellow = Colour("\u001B[32m Yellow \u001B[0m")
)
var Colours = []Colour{
red, green, yellow,
}
func nextColour(currentColour Colour) Colour {
switch currentColour {
case red:
return green
case green:
return yellow
case yellow:
return red
default:
return red
}
}
func main() {
var quitChannel = make(chan string)
var northColour = make(chan Colour, 2)
var southColour = make(chan Colour, 2)
var eastColour = make(chan Colour, 2)
var westColour = make(chan Colour, 2)
var northDirection = make(chan string, 4)
var southDirection = make(chan string, 4)
var eastDirection = make(chan string, 4)
var westDirection = make(chan string, 4)
go TrafficLight(north, northColour, southColour, northDirection, eastDirection, southDirection)
go TrafficLight(south, southColour, northColour, southDirection, westDirection, northDirection)
go TrafficLight(east, eastColour, westColour, eastDirection, southDirection, westDirection)
go TrafficLight(west, westColour, eastColour, westDirection, northDirection, eastDirection)
<-quitChannel
}
func TrafficLight(direction CardinalDirection, currentColour <-chan Colour, oppositeColour chan<- Colour, currentDirection <-chan string, nextDirection chan<- string, oppositeDirection chan<- string) {
var colour = red
if direction != north && direction != south {
nextDirection <- "go"
}
for {
show(direction, colour)
oppositeColour <- nextColour(colour)
select {
case msg := <-currentColour:
if msg == nextColour(colour) {
colour = msg
}
}
}
}
func show(direction CardinalDirection, colour Colour) {
fmt.Println(string(direction), " : ", string(colour))
}
func debug(message string) {
if debuggingAllowed {
fmt.Println("Debug:", message)
}
}