go map结构是否线程安全?

huangapple go评论180阅读模式
英文:

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

自从Go 1.9以来,最好的方法是使用sync.Map类型。

英文:

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

huangapple
  • 本文由 发表于 2010年1月3日 09:23:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/1993586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定