开发者

Is the go map structure thread-safe?

Is the Go map type thread safe? I have a program that has many goroutines reading and wri开发者_运维问答ting to a map type. If I need to implement a protection mechanism, what's the best way to do it?


You'd want to use goroutines and synchronize access to your maps via channels. Explanation from the FAQ:

After long discussion it was decided that the typical use of maps did not require safe access from multiple threads, and in those cases where it did, the map was probably part of some larger data structure or computation that was already synchronized. Therefore requiring that all map operations grab a mutex would slow down most programs and add safety to few. This was not an easy decision, however, since it means uncontrolled map access can crash the program.

The language does not preclude atomic map updates. When required, such as when hosting an untrusted program, the implementation could interlock map access.


Since Go 1.9 the best way is to use sync.Map type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜