3
下面的代碼有時會輸出2。爲什麼不是所有的等候隊都等待完成?爲什麼WaitGroup有時不等所有的goroutines?
type Scratch struct {
//sync.RWMutex
Itch []int
}
func (s *Scratch) GoScratch(done chan bool, j int) error {
var ws sync.WaitGroup
if len(s.Itch) == 0 {
s.Rash = make([]int, 0)
}
for i := 0; i < j; i++ {
ws.Add(1)
go func (i int) {
defer ws.Done()
s.Rash = append(s.Rash, i)
}(i)
}
ws.Wait()
done<- true
return nil
}
func main() {
done := make(chan bool, 3)
s := &Scratch{}
err := s.GoScratch(done, 3)
if err != nil {
log.Println("Error:%v",err)
}
<-done
log.Println("Length: ", len(s.Rash))
}`
奇怪的是我不能得到它輸出2與主要功能,但是當我使用測試用例有時它輸出2。
我不知道我錯過了什麼 - 應該休息一下。謝謝, – Sridhar
有時候,你可以使用一個緩衝通道來替代使用一個片的互斥體。 https://play.golang.org/p/CGdz4T2Qn5 – Billy