-1

The code like:

    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
        }()
    }

There are 10000 read goroutine access m,and another 10000 write goroutine assign a new map to m, and it's safety?

G.yang
  • 347
  • 2
  • 10

1 Answers1

5

You have goroutines reading the m varaible, and goroutines writing the m variable without explicit synchronization. This is a data race, and therefore undefined behaviour.

Run it with the race detector enabled:

$ 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

See related questions:

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

Also an example which breaks Go's memory safety with intentional data race: Golang data races to break memory safety

icza
  • 389,944
  • 63
  • 907
  • 827
  • but it dosen't panic the goroutine? it will only cause some goroutines to read old data. – G.yang May 06 '19 at 10:02
  • Go map is implemented with a pointer.Assign a map to a another map like pointer assignement – G.yang May 06 '19 at 10:04
  • 2
    @G.yang The behavior is undefined. If "sometimes" it works for your that also falls under the "undefiend" behavior. It might break miserable at other times or on other platforms. Don't play with the devil, just use proper synchronization. – icza May 06 '19 at 10:05
  • 2
    @G.yang And it doesn't matter if maps are pointers under the hood or not. Reading the map pointer and changing it is no exception to the race condition. Read the linked questions / articles for details / examples. – icza May 06 '19 at 10:06