map
동시 읽기 안전합니다. 원하는지도를 sync/atomic.Value
안에 넣을 수 있습니다. 쓰기를 원하면지도를 복제하고 변경 한 다음 Value
안에 다시 넣으십시오. docs에서 :
다음은 확장 성이 자주 읽기를 유지하는 방법을 보여줍니다,하지만 자주 업데이트 된 데이터 구조는 관용구를 기록 중 복사 사용.
코드 :
type Map map[string]string
var m Value
m.Store(make(Map))
var mu sync.Mutex // used only by writers
// read function can be used to read the data without further synchronization
read := func(key string) (val string) {
m1 := m.Load().(Map)
return m1[key]
}
// insert function can be used to update the data without further synchronization
insert := func(key, val string) {
mu.Lock() // synchronize with other potential writers
defer mu.Unlock()
m1 := m.Load().(Map) // load current value of the data structure
m2 := make(Map) // create a new value
for k, v := range m1 {
m2[k] = v // copy all data from the current object to the new one
}
m2[key] = val // do the update that we need
m.Store(m2) // atomically replace the current object with the new one
// At this point all new readers start working with the new version.
// The old version will be garbage collected once the existing readers
// (if any) are done with it.
}
_, _ = read, insert
당신은 또한 map
대신 Value
에 대한 포인터를 사용할 수하고 StorePointer/LoadPointer를 사용하여 원자 저장하지만 안전하지 않은 포인터를 사용하고 캐스팅해야 원인이 청소기 아니다.
['RWMutex'] (https://godoc.org/sync#RWMutex)를 사용하여'map [string] struct {}'를 벤치 마크 했습니까? –
[This hasmap package] (https://github.com/cornelk/hashmap)는 사용자의 요구에 맞을 수 있습니다. – bigless
초당 얼마나 많은 조회가 여기에서하고 있습니까? 총 키는 몇 개입니까? 제거와 삽입이 드물다고합니다. 얼마나 드문 일입니까? 저에게 해시 맵 (hashmap)과 리더/라이터 잠금 장치가 매우 효과적이라고 들립니다. https://stackoverflow.com/questions/19148809/how-to-use-rwmutex-in-golang을 참조하십시오. –