Golang:从带有互斥锁的哈希映射中读取的最佳方法

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

Golang: Best way to read from a hashmap w/ mutex

问题

这是从这里继续的:https://stackoverflow.com/questions/17890830/golang-shared-communication-in-async-http-server

假设我有一个带锁的哈希映射:

//为了在请求之间进行通信,创建异步哈希映射
type state struct {
    *sync.Mutex // 继承锁定方法
    AsyncResponses map[string]string // 将id映射到值
}
var State = &state{&sync.Mutex{}, map[string]string{}}

写入此哈希映射的函数将会加锁。我的问题是,有没有一种最好/最快的方法让另一个函数在不阻塞对哈希映射的写入的情况下检查一个值?我想要在值出现时立即知道。

MyVal = State.AsyncResponses[MyId]
英文:

This is a continuation from here: https://stackoverflow.com/questions/17890830/golang-shared-communication-in-async-http-server

Assuming I have a hashmap w/ locking:

//create async hashmap for inter request communication
type state struct {
    *sync.Mutex // inherits locking methods
    AsyncResponses map[string]string // map ids to values
}
var State = &state{&sync.Mutex{}, map[string]string{}}

Functions that write to this will place a lock. My question is, what is the best / fastest way to have another function check for a value without blocking writes to the hashmap? I'd like to know the instant a value is present on it.

MyVal = State.AsyncResponses[MyId]

答案1

得分: 5

读取共享地图而不阻塞写入者是数据竞争的定义。实际上,即使在读取期间写入者被阻塞,从语义上讲,这仍然是一种数据竞争!因为一旦你完成读取值并解除写入者的阻塞 - 值可能不再存在于地图中。

无论如何,在许多程序中,适当的同步很少会成为瓶颈。即使在中等功率的CPU上,{RW,}Mutex的非阻塞锁的开销也可能小于20纳秒。我建议在确保程序正确之后,不仅要进行优化,还要在测量时间的主要部分之后再进行优化。

英文:

Reading a shared map without blocking writers is the very definition of a data race. Actually, semantically it is a data race even when the writers will be blocked during the read! Because as soon as you finish reading the value and unblock the writers - the value may not exists in the map anymore.

Anyway, it's not very likely that proper syncing would be a bottleneck in many programs. A non-blocking lock af a {RW,}Mutex is probably in the order of < 20 nsecs even on middle powered CPUS. I suggest to postpone optimization not only after making the program correct, but also after measuring where the major part of time is being spent.

huangapple
  • 本文由 发表于 2013年8月1日 02:03:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/17977647.html
匿名

发表评论

匿名网友

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

确定