2016-09-08 1 views
-1

Ich bin neu in der Go Sprache und Lernen hier: https://tour.golang.org/concurrency/1A Tour of Go Beispiel auf Goroutines Gleichzeitigkeit

Wenn ich laufe https://play.golang.org/p/9JvbtSuv5o das Ergebnis:

world 
hello 
hello 

sync.WaitGroup So Hinzugefügt: https://play.golang.org/p/vjdhnDssGk

package main 

import (
    "fmt" 
    "sync" 
    "time" 
) 

var w sync.WaitGroup 

func say(s string) { 
    for i := 0; i < 2; i++ { 
     time.Sleep(100 * time.Millisecond) 
     fmt.Println(s) 
    } 
    w.Done() 
} 

func main() { 
    w.Add(1) 
    go say("world") 
    say("hello") 
    w.Wait() 
} 

Aber das Ergebnis ist gleich:

world 
hello 
hello 

Was ist falsch an meinem Code?

Bitte helfen,
Vielen Dank für Ihre Hilfe.

Antwort

0

w.Done() dekrementiert den Zähler WaitGroup.
So Ihr Code sogar manchmal Panik: Sync: negative WaitGroup Zähler.

Sie haben zwei Goroutines:
1-go say("world")
2-say("hello") innen main Goroutine
so w.Add(2) verwenden, finden Sie in diesem Arbeitsprobe (The Go Playground):

package main 

import (
    "fmt" 
    "sync" 
    "time" 
) 

var w sync.WaitGroup 

func say(s string) { 
    for i := 0; i < 2; i++ { 
     time.Sleep(100 * time.Millisecond) 
     fmt.Println(s) 
    } 
    w.Done() 
} 

func main() { 
    w.Add(2) 
    go say("world") 
    say("hello") 
    w.Wait() 
} 

Ausgabe:

world 
hello 
hello 
world 

Ich hoffe, das hilft.

0

Sie fügen der WaitGroup nur 1 hinzu, rufen jedoch aus 2 Aufrufen von say Fertig.

In Ihrem Beispiel würde die WaitGroup beginnend mit 2 arbeiten

w.Add(2) 
0

Problem wegen unbedingter Aufruf w.Done auftritt(). Wenn du also "hallo" sagst, wird auch der Zähler für waitGroup dekrementiert.

Siehe https://play.golang.org/p/wJeAyYyjA2

package main 

    import (
     "fmt" 
     "sync" 
     "time" 
    ) 

    var w sync.WaitGroup 

    func say(s string, async bool) { 
     if async { 
      defer w.Done() 
     } 
     for i := 0; i < 2; i++ { 
      time.Sleep(100 * time.Millisecond) 
      fmt.Println(s) 
     } 
    } 

    func main() { 
     w.Add(1) 
     go say("world", true) 
     say("hello", false) 
     w.Wait() 
    }