Home >Backend Development >Golang >Why Does `recover` Fail to Handle Concurrent Map Modification Crashes in Go?
Handling Concurrent Map Modifications: A Recover vs. Runtime Crash Dilemma
When dealing with concurrent map access, one might encounter a peculiar situation where recovering from a "concurrent map read and map write" panic seems futile. This is because the runtime's behavior in such cases is not a panic but a deliberate crash.
In Go 1.6, the runtime introduced a detection mechanism for concurrent misuse of maps. If multiple goroutines attempt to modify a map concurrently, the runtime triggers a crash, printing a diagnostic message. This behavior stems from the inherent danger of potential undefined behavior when maps are accessed concurrently for write operations.
Unfortunately, the typical approach of using defer with recover to handle panics is ineffective in this scenario. The recover function cannot intercept the crash initiated by the runtime. The recommended solution is to prevent the concurrent misuse of maps altogether.
In the provided 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) }
The concurrent writes to the map "m" will trigger the runtime crash. To prevent this, one would need to employ synchronization mechanisms, such as using a mutex or a channel, to ensure exclusive access to the map during write operations.
The above is the detailed content of Why Does `recover` Fail to Handle Concurrent Map Modification Crashes in Go?. For more information, please follow other related articles on the PHP Chinese website!