将地图分配给另一个地图在golang中安全吗?

时间:2019-05-06 08:49:39

标签: go

类似的代码:

    m := make(map[interface{}]interface{})
    //read
    for i := 0; i< 10000; i++ {
        go func() {
            for range m {

            }
        }()
    }
    //write
    for i := 0; i< 10000; i++ {
        go func() {
            mTemp := make(map[interface{}]interface{})
            m = mTemp
        }()
    }

有10000个读goroutine访问m,另一个10000个写goroutine访问m,这是安全的吗?

1 个答案:

答案 0 :(得分:4)

您有goroutines读取m变量,而goroutines则写入m变量而没有显式同步。这是一场数据竞赛,因此行为不确定。

在启用种族检测器的情况下运行它:

$ go run -race play.go
==================
WARNING: DATA RACE
Write at 0x00c00008c000 by goroutine 15:
  main.main.func2()
      /home/icza/gows/src/play/play.go:17 +0x46

Previous read at 0x00c00008c000 by goroutine 5:
  main.main.func1()
      /home/icza/gows/src/play/play.go:8 +0x45

Goroutine 15 (running) created at:
  main.main()
      /home/icza/gows/src/play/play.go:15 +0xdd

Goroutine 5 (finished) created at:
  main.main()
      /home/icza/gows/src/play/play.go:7 +0xa4
==================
Found 1 data race(s)
exit status 66

查看相关问题:

Is it safe to read a function pointer concurrently without a lock?

还有一个通过故意的数据争夺破坏Go的内存安全性的示例:Golang data races to break memory safety