dourang6423 2015-07-13 23:45
浏览 38
已采纳

被取消引用的指针的类型断言是否是在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.

  • 写回答

1条回答 默认 最新

  • dqy1265 2015-07-14 00:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?