2017-12-31 16 views
0

32 바이트 문자열을 저장하고 원하는 O (1) 또는 O (log N) 조회 복잡도로 빠른 검색을 허용하는 데이터 구조를 찾고 있습니다. 키가 있음). 삭제 및 삽입의 복잡성은 중요하지 않습니다. 이러한 작업은 자주 발생하지 않기 때문입니다.concurnt 무거운 읽기 작업 부하에 대한 데이터 구조

질문과 관련이 없지만 Go에서 근무하고 있습니다. 내가 hashmap 뮤텍스에 의해 뒷받침 할 수 있지만, 경합이 문제가 될 수 있으며 더 나은 솔루션이 있다면 sharding을 피하는 것을 선호한다.

감사

+0

['RWMutex'] (https://godoc.org/sync#RWMutex)를 사용하여'map [string] struct {}'를 벤치 마크 했습니까? –

+1

[This hasmap package] (https://github.com/cornelk/hashmap)는 사용자의 요구에 맞을 수 있습니다. – bigless

+0

초당 얼마나 많은 조회가 여기에서하고 있습니까? 총 키는 몇 개입니까? 제거와 삽입이 드물다고합니다. 얼마나 드문 일입니까? 저에게 해시 맵 (hashmap)과 리더/라이터 잠금 장치가 매우 효과적이라고 들립니다. https://stackoverflow.com/questions/19148809/how-to-use-rwmutex-in-golang을 참조하십시오. –

답변

0

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를 사용하여 원자 저장하지만 안전하지 않은 포인터를 사용하고 캐스팅해야 원인이 청소기 아니다.

관련 문제