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.

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

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写