golang struct concurrent read and write without Lock is also running ok?

时光怂恿深爱的人放手 提交于 2019-11-28 12:55:41

Unsynchronized, concurrent access to any variable from multiple goroutines where at least one of them is a write is undefined behavior. Do not try to find logic in undefined behavior, just use proper synchronization. Undefined means it may run "correctly" or it may run "incorrectly" (giving incorrect results), or it may crash or anything else. That's what undefined means. Read more about it here: Is it safe to read a function pointer concurrently without a lock?

Your concurrentStructWithMuLock() has actually no data race, because you are using a mutex to properly synchronize access to the struct.

And with concurrentMap() that's another issue. Go 1.6 added a lightweight concurrent misuse of maps detection to the runtime:

The runtime has added lightweight, best-effort detection of concurrent misuse of maps. As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. If the runtime detects this condition, it prints a diagnosis and crashes the program. The best way to find out more about the problem is to run the program under the race detector, which will more reliably identify the race and give more detail.

So this is an intentional crash by the runtime, because it detects unsynchronized access to the map. This is a "feature" of the Go runtime, and it crashes your app because no data race should be left in your app (to prevent undefined behavior). Read more about it here: How to recover from concurrent map writes?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!