这是此处的延续:Golang:异步http服务器中的共享通信
假设我有一个带锁定的hashmap:
//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{}}
Run Code Online (Sandbox Code Playgroud)
写入此函数将触发锁定.我的问题是,在不阻止写入hashmap的情况下,让另一个函数检查值的最佳/最快方法是什么?我想知道它上面有一个值的瞬间.
MyVal = State.AsyncResponses[MyId]
Run Code Online (Sandbox Code Playgroud)
在不阻塞编写器的情况下读取共享映射是数据竞争的定义.实际上,从语义上来说,即使在读取期间编写器被阻止,它仍然是数据竞争!因为只要您完成读取值并取消阻止编写者 - 该值可能不再存在于地图中.
无论如何,正确的同步不太可能成为许多程序的瓶颈.即使在中等功率的CPUS上,{RW,} Mutex的非阻塞锁也可能在<20 nsecs的数量级.我建议不仅在使程序正确之后推迟优化,而且在测量花费大部分时间之后.