0

I know that go maps are not safe for concurrent access, but what happens if I do access them concurrently? Are they safe for concurrent read-access? Could I break it to a point where it loses all or some of its data? Is there a point where the whole program could crash if I modify it and read it at the same time? Do I need to have two different processes modifying it concurrently to mess things up?

I'm interested in both the standard go compiler, and gccgo.

What can happen if I concurrently access/modify a go map?

Filip Haglund
  • 13,919
  • 13
  • 64
  • 113
  • They are safe for concurrent read (all types are), but I don't know about what exact exciting ways maps can break on concurrent writes. My guess is the biggest danger is at reallocation or hash collision. – Linear Jan 11 '16 at 22:59
  • Some data structures modify state on reads. Trees using the rotate-to-root heuristic is one example. – Filip Haglund Jan 11 '16 at 23:01
  • IIRC the recommended way to isolate a map for thread safety is a RWLock, which implies that concurrent reads are okay as long as there aren't any writes. – Not_a_Golfer Jan 11 '16 at 23:08
  • 2
    You will corrupt the internal state of the map (and possibly other memory). In go1.6 there is new check that will crash your app with the message "concurrent map writes" or "concurrent map read and map write" in cases where it can be detected. – JimB Jan 11 '16 at 23:09
  • 1
    reference on this - https://blog.golang.org/go-maps-in-action seems that concurrent read access is supported as a defined behavior. – Not_a_Golfer Jan 11 '16 at 23:09
  • 2
    @FilipHaglund What I meant by "all types are safe for concurrent read" is that if you can read them without calling a function. The second there's a function call involved in the read (which is what would be required for the tree example) all bets are off unless concurrency is documented. This is true of all builtin go types. (i.e. it's safe to read an arbitrary struct with `=` too) – Linear Jan 11 '16 at 23:15

0 Answers0