Go map类型的线程安全吗? 我有一个程序,其中有许多goroutine可以读写地图类型。 如果需要实施保护机制,什么是最好的方法?


您想使用goroutines并通过渠道同步对地图的访问。 常见问题解答中的说明:

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.


从1.9开始,最好的方法是使用sync.Map类型。