dongtao5104 2016-08-16 16:59
浏览 20
已采纳

为什么这个WaitGroup有时不等待所有goroutine?

The code below outputs 2 sometimes. Why isn't the wait group waiting for all the goroutines to complete ?

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)) 
}`

Strangely i can't get it to output 2 with a main function but when I use a test case it outputs 2 sometimes.

  • 写回答

2条回答 默认 最新

  • doutouhe5343 2016-08-16 17:07
    关注

    There is a race condition in your code. It is right here:

    go func (i int) {
        defer ws.Done()
        // race condition on s.Rash access
        s.Rash = append(s.Rash, i) 
    }(i)
    

    Since all the goroutines access s.Rash concurrently, this may cause the slice updates to be overwritten. Try running the same code with sync.Mutex locking to prevent this:

    // create a global mutex
    var mutex = &sync.Mutex{}
    
    // use mutex to prevent race condition
    go func (i int) {
        defer ws.Done()
        defer mutex.Unlock() // ensure that mutex unlocks
    
        // Lock the resource before accessing it
        mutex.Lock()
        s.Rash = append(s.Rash, i) 
    }(i)
    

    You can read more about this here and here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ 菜单窗口独立出来,可以随意移动放大缩小。
  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 网友们我该怎么办啊,急
  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上
  • ¥15 目标跟踪,计算机视觉
  • ¥15 魔霸ROG7 pro,win11.息屏后会显示黑屏,如图,如何解决?(关键词-重新启动)
  • ¥15 有没有人知道这是哪里出了问题啊?要怎么改呀?