110 lines
2.1 KiB
Go
110 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime"
|
|
)
|
|
|
|
//Definition CardinalDirection als enum
|
|
type CardinalDirection int
|
|
|
|
const (
|
|
north = iota
|
|
east
|
|
south
|
|
west
|
|
)
|
|
|
|
//definiert die nächste Richtung in der Reihenfolge north -> east -> south -> west -> north ...
|
|
func nextDirection(direction CardinalDirection) CardinalDirection {
|
|
return (direction + 1) % (west + 1)
|
|
}
|
|
|
|
func (direction CardinalDirection) String() string {
|
|
return [...]string{"North", "East", "South", "West"}[direction]
|
|
}
|
|
|
|
//Definition Colour als enum
|
|
type Colour int
|
|
|
|
const (
|
|
red Colour = iota
|
|
green
|
|
yellow
|
|
)
|
|
|
|
//definiert nächste Farbe in der Reihenfolge red -> green -> yellow -> red ...
|
|
func nextColour(colour Colour) Colour {
|
|
return (colour + 1) % (yellow + 1)
|
|
}
|
|
|
|
func (colour Colour) String() string {
|
|
return [...]string{"Red", "Green", "Yellow"}[colour]
|
|
}
|
|
|
|
//Erstellung der Channel
|
|
var northSouthChannel = make(chan string)
|
|
var eastWestChannel = make(chan string)
|
|
|
|
//Channel für die Achse erhalten, zu der direction gehört
|
|
func getAxisChannel(direction CardinalDirection) chan string {
|
|
if direction == north || direction == south {
|
|
return northSouthChannel
|
|
} else {
|
|
return eastWestChannel
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
var quitChannel = make(chan string)
|
|
|
|
go TrafficLight(north)
|
|
go TrafficLight(south)
|
|
go TrafficLight(east)
|
|
go TrafficLight(west)
|
|
|
|
<-quitChannel
|
|
}
|
|
|
|
func TrafficLight(direction CardinalDirection) {
|
|
var colour = red
|
|
|
|
if direction == east || direction == west {
|
|
handover("changeDirection", direction)
|
|
}
|
|
|
|
for {
|
|
show(direction, colour)
|
|
|
|
if colour == red {
|
|
sync("wait", direction)
|
|
handover("changeDirection", direction)
|
|
runtime.Gosched()
|
|
}
|
|
sync("changeLight"+nextColour(colour).String(), direction)
|
|
colour = nextColour(colour)
|
|
}
|
|
}
|
|
|
|
func handover(message string, direction CardinalDirection) {
|
|
getAxisChannel(nextDirection(direction)) <- message
|
|
|
|
select {
|
|
case <-getAxisChannel(direction):
|
|
}
|
|
|
|
}
|
|
|
|
func sync(message string, direction CardinalDirection) {
|
|
|
|
select {
|
|
case getAxisChannel(direction) <- message:
|
|
case <-getAxisChannel(direction):
|
|
}
|
|
|
|
}
|
|
|
|
func show(direction CardinalDirection, colour Colour) {
|
|
fmt.Println(direction.String(), " : ", colour.String())
|
|
}
|