扫码一下
查看教程更方便
解析:
官方解释:
maps are not safe for concurrent use: it’s not defined what happens when you read and write to them simultaneously. if you need to read from and write to a map from concurrently executing goroutines, the accesses must be mediated by some kind of synchronization mechanism. one common way to protect maps is with sync.rwmutex.
大致意思就是说,并发访问map是不安全的,会出现未定义行为,导致程序退出。所以如果希望在多协程s)中并发访问map,必须提供某种同步机制,一般情况下通过读写锁sync.rwmutex实现对map的并发访问控制,将map和sync.rwmutex封装一下,可以实现对map的安全并发访问。
同时go1.9版本之后,已经支持,sync包下:
func (m *map) delete(key interface{})
func (m *map) load(key interface{}) (value interface{}, ok bool)
func (m *map) loadorstore(key, value interface{}) (actual interface{}, loaded bool)
func (m *map) range(f func(key, value interface{}) bool)
func (m *map) store(key, value interface{})