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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64