【发布时间】:2016-08-16 16:59:06
【问题描述】:
下面的代码有时会输出 2。为什么等待组不等待所有 goroutine 完成?
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))
}`
奇怪的是,我无法通过 main 函数将其输出 2,但是当我使用测试用例时,它有时会输出 2。
【问题讨论】:
标签: go concurrency