/* Landesamt für Geoinformation und Landentwicklung, Referat 35 Einführung in die Sprache Go, 25.7.2017 Lektion 6: Kommunikation zwischen nebenläufigen Prozessen: "Share memory by communicating, don't communicate by sharing memory." */ package main import ( "fmt" "math" "math/rand" "runtime" "sync" "time" ) const ( anzahlTöpfchen int8 = 25 anzahlKugeln int32 = 100000 ) var timestamp [2]int64 var wg, wg2 sync.WaitGroup // ! func main() { runtime.GOMAXPROCS(runtime.NumCPU()) timestamp[0] = time.Now().UnixNano() var töpfchenAlle []int = make([]int, anzahlTöpfchen, anzahlTöpfchen) var c chan bool = make(chan bool, 1) // ! wg2.Add(1) go func(t *[]int, ch chan bool) { // ! defer wg2.Done() for true { /* Bringt nichts, weil auf <-ch == true gewartet werden müßte: time.Sleep(time.Second * 1) if <-ch == true { return } else { }*/ /*stattdessen:*/ select { case <-ch: // oder <-ch == true return default: fmt.Println("\u231B", *t, runtime.NumGoroutine()) time.Sleep(time.Second * 1) } } }(&töpfchenAlle, c) for k := (int32)(1); k <= anzahlKugeln; k++ { wg.Add(1) go zeigeMirDenGauß(int(anzahlKugeln), int(anzahlTöpfchen), &töpfchenAlle) for runtime.NumGoroutine() >= 50 { // Limitiere die Anzahl der go-Routinen time.Sleep(time.Millisecond * 1) } } wg.Wait() c <- true wg2.Wait() close(c) fmt.Println("\u2690", töpfchenAlle) timestamp[1] = time.Now().UnixNano() fmt.Printf("\nProzess ist fertig und hat %v Sekunden gedauert!\n\n", (float64(timestamp[1]-timestamp[0]) * math.Pow(10, -9))) } func zeigeMirDenGauß(anzahlKugeln int, anzahlTöpfchen int, töpfchenAlle *[]int) { defer wg.Done() var töpfchenTmpZähler int for i := 0; i < anzahlTöpfchen-1; i++ { if yesnotrigger := func() bool { if rand.New(rand.NewSource(time.Now().UnixNano())).Float64() < 0.5 { return true } else { return false } }(); yesnotrigger == true { töpfchenTmpZähler++ } } (*töpfchenAlle)[töpfchenTmpZähler]++ }