在Go语言中,我们可以使用每个键一个锁来同步映射的每个键吗?

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

In Go, can we synchronize each key of a map using a lock per key?

问题

在Go语言中,我们可以使用每个键一个锁来同步map吗?是否总是需要对整个map进行全局锁定?文档中提到,对map的任何访问都不是线程安全的。但是,如果一个键存在,那么可以单独对其进行锁定吗?

英文:

In Go, can we synchronize each key of a map using a lock per key?
Is map level global lock always required?
The documentation says that any access to map is not thread safe. But if a key exists, then can it be locked individually?

答案1

得分: 1

并不完全准确,但如果你只是从地图上读取指针并修改引用对象,那么你并没有修改地图本身。

英文:

Not exactly, but if you are only reading pointers off a map and modifying the referents, then you aren't modifying the map itself.

答案2

得分: 1

这是你想要的简单实现:mapmutex

基本上,互斥锁被用来保护地图,地图中的每个项目都像一个“锁”一样使用。

英文:

This is a simple implementation of what you want: mapmutex.

Basically, a mutex is used to guard the map and each item in the map is used like a 'lock'.

huangapple
  • 本文由 发表于 2016年11月12日 13:54:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/40560007.html
匿名

发表评论

匿名网友

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

确定