doufunuo4787 2016-09-23 15:59
浏览 10

如何正确防止数据争用?

According to the docs doing the following prevents a data race:

    var wg sync.WaitGroup
    wg.Add(5)
    for i := 0; i < 5; i++ {
        go func(j int) {
            fmt.Println(j) // Good. Read local copy of the loop counter.
            wg.Done()
        }(i)
    }
    wg.Wait()

however if I have code such as:

type Job struct {
    Work []string
}

var Queue chan Job


func work(id string, type int32) {

    job := Job{Work: []string{"A","B","C"}}

    go func(j Job, ty int32) {
        if ty == 1 {
        // do some other task
        }
        Queue <- j
    } (job, type) // RACE ON THIS LINE

    if type == 1 {
        // do something
    }

    return
}

work is being called via. gRPC.

the data race detector tells me that the go routine is producing a data race. I am thinking that there is something I am missing here but can't quite seem to find what that is.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看