dreamy1992 2018-10-08 22:25
浏览 353
已采纳

len()线程在golang中安全吗?

I'm logging every second the length of a map; I don't care if I have the "exact" value / race conditions (off by one is ok). I'm interested to know if this could cause a panic and if I have to enclose len() with some .RLock()/Unlock() or not.

I'm asking because concurrent reads/writes in a map will cause a panic (Go detects that) but I don't know if reading the length counts as a "read". I have tried with a test program but cannot produce a crash but I'd rather have an exact answer, at least for the sake of it.

If it matters I'm interested in both len for arrays and for maps. Thanks!

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-10-08 22:44
    关注

    It is a race condition. The results are undefined. For example,

    racer.go:

    package main
    
    func main() {
        m := make(map[int]int)
        l := 0
        go func() {
            for {
                l = len(m)
            }
        }()
        for i := 0; i < 10000; i++ {
            m[i] = i
        }
    }
    

    Output:

    $ go run -race racer.go
    ==================
    WARNING: DATA RACE
    Read at 0x00c00008e000 by goroutine 5:
      main.main.func1()
          /home/peter/gopath/src/racer.go:8 +0x5f
    
    Previous write at 0x00c00008e000 by main goroutine:
      runtime.mapassign_fast64()
          /home/peter/go/src/runtime/map_fast64.go:92 +0x0
      main.main()
          /home/peter/gopath/src/racer.go:12 +0xba
    
    Goroutine 5 (running) created at:
      main.main()
          /home/peter/gopath/src/racer.go:6 +0x92
    ==================
    Found 1 data race(s)
    exit status 66
    $
    

    References:

    Wikipedia: Race condition

    The Go Blog: Introducing the Go Race Detector

    Go: Data Race Detector

    Benign Data Races: What Could Possibly Go Wrong?

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

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载