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 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下