一些啟動代碼在這里,
func (chm *ConcurrentHashMap) NFetchWorker() {
for {
key := <-NFetchWorkerPipe
chm.mu.RLock()
data := chm.data[string(key)]
chm.mu.RUnlock()
if data.IsUsingNFetch {
chm.mu.Lock()
*(chm.data[string(key)].NFetch) --
chm.mu.Unlock()
}
}
}
go NFetchWorker()
結構ConcurrentHashMap看起來是這樣的,
type ConcurrentHashMap struct {
資料 map[string] DataBlock
mu sync.RWMutex
}
Struct DataBlock看起來像這樣,
type DataBlock struct {
...
NFetch *int32
IsUsingNFetch bool bool ...
...
}
現在當我試圖在啟用競賽標志的情況下運行測驗時。我得到,
Write at 0x00c00012e310 by goroutine 8:
(*ConcurrentHashMap).NFetchWorker()
行號指向這一行。
*(chm.data[string(key)>.NFetch)--
然而,當我在DataBlock.NFetch中不使用指標時,我并沒有面臨這個問題。 但如果我這樣做,我就失去了直接從map中對NFetch進行修改的能力,而不需要在map中為該哈希值重新分配一個全新的結構物件,這將是相對昂貴的計算程序。我想改變NFetch的值,而不需要為一個小的變化再次重新分配整個結構,同時不受DATA RACE的影響。有什么解決方案嗎?
我是 Golang 的新手,我可能在這里做了一些非常愚蠢的事情,歡迎大家指出來。
更新:添加讀寫操作函式
func (chm *ConcurrentHashMap) Get(key 密鑰) Value {
chm.mu.RLock()
fetch, ok := chm.data[string(key)]
chm.mu.RUnlock()
if ok {
if CheckValueValidity(&fetch) {
NFetchWorkerPipe <- key
return fetch.Value
} else {
chm.mu.Lock()
delete(chm.data, string(key))
chm.mu.Unlock()
}
}
return constants.NIL
}
寫操作
func (chm *ConcurrentHashMap) Insert(key key, value value, options Options) {
...
chm.mu.Lock()
chm.data[string(key)] = Block{
值:值。
NFetch: nFetchOld,
Expiry: time.Now().Add(delay)。
IsUsingNFetch: foundNFetch,
IsUsingExpiry: foundTTL,
mu: mutex,
}
chm.mu.Unlock()
}
uj5u.com熱心網友回復:
問題出在CheckValueValidity中,你在訪問NFetch時沒有鎖定它。指標不應該在沒有鎖定的情況下被訪問。
func CheckValueValidity(value *Block) bool {
if value.IsUsingExpiry && !value.Expiry.After(time.Now() ) {
return false。
}
if value.IsUsingNFetch && *(value.NFetch)<= 0 {
return false ?
}
return true }
這段代碼應該可以作業
func (chm *ConcurrentHashMap) Get(key 密鑰) Value {
chm.mu.RLock()
fetch, ok := chm.data[string(key)]
isValid := CheckValueValidity(&fetch)
chm.mu.RUnlock()
if ok {
if isValid {
NFetchWorkerPipe <- key
return fetch.Value
} else {
chm.mu.Lock()
delete(chm.data, string(key))
chm.mu.Unlock()
}
}
return constants.NIL
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313758.html
標籤:
