英文:
Is the go map structure thread-safe?
问题
Go的map类型是线程安全的吗?我有一个程序,其中有许多goroutine读写map类型。如果我需要实现保护机制,最好的方法是什么?
英文:
Is the Go map type thread safe? I have a program that has many goroutines reading and writing to a map type. If I need to implement a protection mechanism, what's the best way to do it?
答案1
得分: 18
你应该使用goroutines,并通过channels来同步访问你的maps。来自FAQ的解释:
> 经过长时间的讨论,决定了maps的典型用法不需要从多个线程安全地访问,而在那些需要的情况下,map可能是某个更大的数据结构或计算的一部分,而这些已经被同步。因此,要求所有的map操作都获取一个互斥锁会减慢大多数程序的速度,并且只为少数程序增加安全性。这并不是一个容易的决定,因为它意味着不受控制的map访问可能会导致程序崩溃。
>
> 语言并不排除原子map更新的可能性。当需要时,比如在托管一个不受信任的程序时,实现可以交错地访问map。
英文:
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.
答案2
得分: 6
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论