被取消引用的指针的类型断言是否是在go中写入的内存?
The go race detector complains about my code in a way that makes no sense to me, but I guess that the authors of the race detector know more about this than I do.
I have this closure:
func(f *datastore.F) bool {
a, ok := (*f).(*datastore.T)
...
}
that I pass as an argument to this function:
func GetFunc(f func(fid *datastore.F) bool) (*datastore.F, bool) {
kvs.lock.RLock()
defer kvs.lock.RUnlock()
for _, v := range kvs.fs {
if f(v) {
return v, true
}
}
return nil, false
}
and this is the relevant part of the other goroutine:
for read := range [chan of datastore.F] {
s.lock.Lock()
s.fs[read.Fi()] = &read
s.lock.Unlock()
}
kvs
is an instance of this type:
type kvstore struct {
lock sync.RWMutex
fs map[datastore.Fi]*datastore.F
}
datastore.F
is an interface, and *datastore.T
implements that interface.
The race detector complains that the closure and the other goroutine have a data race. The other goroutine writes and the closure reads. What I don't see is how this could conflict, given the sync.RWMutex
in place.
A type assertion of a dereferenced pointer does not write to a variable in Go.
This code
for read := range [chan of datastore.F] {
s.lock.Lock()
s.fs[read.Fi()] = &read
s.lock.Unlock()
}
sets the map value to the address of the local variable read
. The variable read
has a scope outside the for loop block and is modified on every iteration through the loop. All map values contain the same pointer, which is probably not what you intended.
The closure reads the the variable read
by dereferencing the pointer in the map. The race detector complains because there's no synchronization between the reader (the closure) and the writer (the for loop).
To fix the problem, declare a new variable inside the loop:
for read := range [chan of datastore.F] {
read := read // <-- Add this line
s.lock.Lock()
s.fs[read.Fi()] = &read
s.lock.Unlock()
}
With this change, each map value points to a unique variable that is set once.
It is rare to use pointers to interfaces in Go. The preferred fix to this problem is to change all use of the type *datastore.F
to datastore.F
. This change eliminates references to the the variable read
across goroutine boundaries and eliminates an unnecessary level of indirection.