doudouji2016 2017-02-03 22:41
浏览 34
已采纳

从按值传递的结构值读取字段时发生数据争用

Why does golang race detector complains about the following code:

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    value int
    mtx     *sync.Mutex
}

func NewCounter() *Counter {
    return &Counter {0, &sync.Mutex{}}
}

func (c *Counter) inc() {
    c.mtx.Lock()
    c.value++
    c.mtx.Unlock()
}

func (c Counter) get() int {
    c.mtx.Lock()
    res := c.value
    c.mtx.Unlock()
    return res
}

func main() {
    var wg sync.WaitGroup
    counter := NewCounter()
    max := 100
    wg.Add(max)

    // consumer
    go func() {
        for i := 0; i < max ; i++ {
            value := counter.get()
            fmt.Printf("counter value = %d
", value)
            wg.Done()
        }
    }()
    // producer
    go func() {
        for i := 0; i < max ; i++ {
            counter.inc()
        }
    }()

    wg.Wait()
}

When I run the code above with -race I'm getting the following warnings:

==================
WARNING: DATA RACE
Read at 0x00c0420042b0 by goroutine 6:
  main.main.func1()
      main.go:39 +0x72

Previous write at 0x00c0420042b0 by goroutine 7:
  main.(*Counter).inc()
      main.go:19 +0x8b
  main.main.func2()
      main.go:47 +0x50

Goroutine 6 (running) created at:
  main.main()
      main.go:43 +0x167

Goroutine 7 (running) created at:
  main.main()
      main.go:49 +0x192
==================

If I change func (c Counter) get() int to func (c *Counter) get() int then everything is working fine. It turns out that the receiver type for get() function should be a pointer. And I'm confused why that is. I'm aware of "-copylocks" but in this case mtx is a pointer, not value. If I change 'mtx' to be value and run program with vet -copylocks I get this warning:

main.go:23: get passes lock by value: main.Counter contains sync.Mutex`

That makes sense.

note: This question is not about how to implement thread safe counter

link to playground code

  • 写回答

2条回答 默认 最新

  • dongxi0523 2017-02-03 22:59
    关注

    The race is because of the value receiver for the get() method. In order to call the get() method, a copy of the struct must be passed to the method expression. The method call without the syntactic sugar looks like:

    value := Counter.get(*counter)
    

    Copying the struct entails reading the value field, which happens before the method can take the lock, which is why the race is reported on the line of the method call, rather than within the method.

    This is why changing the receiver to a pointer receiver will fix the issue. Also, since all receivers need to be pointers, the mtx can be left as a sync.Mutex value so it doesn't need to be initialized.

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

报告相同问题?

悬赏问题

  • ¥15 c语言数据结构实验单链表的删除
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline