最佳答案
我正在研究一个并发 Go 库,偶然发现了两种不同的 goroutine 同步模式,它们的结果是相似的:
package main
import (
"fmt"
"sync"
"time"
)
var 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()
}
package main
import (
"fmt"
"time"
)
func main() {
words := []string{"foo", "bar", "baz"}
done := make(chan bool)
// defer close(done)
for _, word := range words {
// fmt.Println(len(done), cap(done))
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
for range words {
<-done
}
}
有人告诉我,sync.WaitGroup
的性能稍微好一点,而且我已经看到它被广泛使用。然而,我发现频道更加地道。在通道上使用 sync.WaitGroup
的真正优势是什么? 当它更好的时候,情况会是怎样?