爲什麼golang比賽探測器抱怨以下代碼:數據讀取賽從按值傳遞結構值場時
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\n", value)
wg.Done()
}
}()
// producer
go func() {
for i := 0; i < max ; i++ {
counter.inc()
}
}()
wg.Wait()
}
當我運行上面-race
我得到以下警告代碼:
==================
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
==================
如果我將func (c Counter) get() int
更改爲func (c *Counter) get() int
那麼一切工作正常。事實證明,get()
函數的接收器類型應該是一個指針。我很困惑這是爲什麼。我知道「-copylocks」,但在這種情況下,mtx
是一個指針,而不是值。如果我改變 'MTX' 是與vet -copylocks
值和運行程序中,我得到這樣的警告:
main.go:23:獲得通行證鎖按值:main.Counter包含sync.Mutex`
這很有道理。
注:這個問題不是關於如何實現線程安全的計數器