我正在开发一个并发 Go 库,我偶然发现了 goroutines 之间的两种不同的同步模式,它们的结果相似:
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.WaitGroupover channel的真正优势是什么和/或当它更好时可能会是什么情况?
慕标5832272
杨魅力
ABOUTYOU
相关分类