0

How to recover from concurrent map writes?

as icza said:

If you would leave your app like that and it wouldn't crash, you could experience mysterious, undefined behavior at runtime.

If one goroutine fails to write to a map in case of "concurrent map writes", how about just panic("concurrent map writes") instead of throw("concurrent map writes").

JimB
  • 104,193
  • 13
  • 262
  • 255
y chen
  • 31
  • 3
  • 2
    What is this "throw" you speak of? – jub0bs Jun 21 '21 at 11:45
  • 4
    What difference would it make? It's still a data race and hence undefined behavior. Use proper synchronization to avoid the concurrent map writes, and so you don't have to worry about either panic nor app crash. – icza Jun 21 '21 at 11:59
  • 4
    the only thing that makes `map` different here is that `map` is a more complex builtin data structure - it holds its own logic and invariance between data in it; a data racing write would cause undefined behaviour and possibly data corruption, which might put the map into invalid state (broken invariance) causing following reading and writing to the map undefined behaviour too. while a `panic` instead of a `throw` would make it recoverable, it makes little sense: data race is not something that should or can be fixed at runtime. – leaf bebop Jun 21 '21 at 12:03
  • 1
    @jub0bs: `throw` is used in the runtime to produce a "fatal error". It's not part of the language spec. – JimB Jun 21 '21 at 12:24
  • 1
    @JimB Thanks. I learned something. For future readers: https://golang.org/src/runtime/panic.go#L1107 – jub0bs Jun 21 '21 at 12:49

1 Answers1

5

The runtime cannot detect races, but it can detect when the internal state of a map has been corrupted by a data race, and that is what throw("concurrent map writes") and throw("concurrent map read and map write") are for (throw is used extensively in the runtime, to abort the program when there is no safe way to proceed). Using a panic here would imply that you can recover from this situation, but there is no way to recover, because it is already known that the program state has been corrupted.

wasmup
  • 14,541
  • 6
  • 42
  • 58
JimB
  • 104,193
  • 13
  • 262
  • 255