私は、同時ゴーライブラリに取り組んでいる、と私は結果と類似しているゴルーチン間の同期の二つの異なるパターンつまずい:sync.WaitGroup over Advantageの利点は何ですか?
チャンネルを使用してWaitgroupvar wg sync.WaitGroup
func main() {
words := []string{ "foo", "bar", "baz" }
for _, word := range words {
wg.Add(1)
go func(word string) {
time.Sleep(1 * time.Second)
defer wg.Done()
fmt.Println(word)
}(word)
}
// do concurrent things here
// blocks/waits for waitgroup
wg.Wait()
}
を使用して
func main() { words = []string{ "foo", "bar", "baz" } done := make(chan bool) defer close(done) for _, word := range words { go func(word string) { time.Sleep(1 * time.Second) fmt.Println(word) done <- true }(word) } // Do concurrent things here // This blocks and waits for signal from channel <-done }
私はsync.WaitGroup
がわずかによりパフォーマンスで、I hのことを助言されましたそれが一般的に使用されているのを見た。しかし、私はより慣用的なチャンネルを見つける。チャネル上でsync.WaitGroup
を使用することの本当のメリットは何ですか?
2番目の例では、同期が間違っています。最初のゴルーチンが最後のチャンネルまでチャンネルを送信するまでブロックします。私はそれがすべてのメンバーをプリントアウトword' 'にゴルーチンの機能に引数を変更したときに何らかの理由でhttps://github.com/golang/go/wiki/MutexOrChannel#wait-group –
はに見てください正しく – molivier
@Not_a_Golfer: – PieOhPah