dswg47377 2015-09-26 23:22
浏览 68
已采纳

sync.WaitGroup的行为异常,在这里我想念的是什么?

Given the following:

package main

import (
    "fmt"
    "sync"
)

func main() {
    n := 100

    var wg sync.WaitGroup
    wg.Add(n)

    x := 0
    for i := 0; i < n; i++ {
        go func() {
            defer wg.Done()
            x++
        }()
    }

    wg.Wait()
    fmt.Println(n, x)
}

I would expect x to always reach 100 by the time it prints at the end, but it sometimes prints as low as 95. What am I missing here?

  • 写回答

2条回答 默认 最新

  • douxieti6851 2015-09-26 23:26
    关注

    There's a race on x. One fix is to protect x with a mutex:

    var mu sync.Mutex
    var wg sync.WaitGroup
    wg.Add(n)
    
    x := 0
    for i := 0; i < n; i++ {
        go func() {
            defer wg.Done()
            mu.Lock()
            x++
            mu.Unlock()
        }()
    }
    
    wg.Wait()
    fmt.Println(n, x)
    

    playground example

    I suggest running the race detector whenever one finds something puzzling in a Go program with more than one goroutine.

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

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答