How do you recover from a runtime panic on a "concurrent map read and map write"? The usual defer with recover doesn't seem to work. Why is that?
I know that you are not supposed to use maps in concurrent contexts, but still: how to recover here?
Example:
package main
import "time"
var m = make(map[string]string)
func main() {
go func() {
for {
m["x"] = "foo"
}
}()
go func() {
for {
m["x"] = "foo"
}
}()
time.Sleep(1 * time.Second)
}
Please add recovery code. :)
Do not recover, guard your code with mutexes form package sync.
Recovering doesn't work here because what you experience is not a panicing state.
Go 1.6 added a lightweight concurrent misuse of maps detection to the runtime:
What you experience is an intentional crash by the runtime, it's not the result of a
panic()
call that arecover()
call in a deferred function could stop.There's nothing you can do to stop that except prevent the concurrent misuse of maps. If you would leave your app like that and it wouldn't crash, you could experience mysterious, undefined behavior at runtime.