我如何概括这种地图访问/修改模式,考虑到go中没有泛型?
func (pool *fPool) fetch(url string) *ResultPromise {
pool.cacheLock.RLock()
if rp, pres := pool.cache[url]; pres {
pool.cacheLock.RUnlock()
return rp
}
pool.cacheLock.RUnlock()
pool.cacheLock.Lock()
if rp, pres := pool.cache[url]; pres {
pool.cacheLock.Unlock()
// Skip adding url if someone snuck it in between RUnlock an Lock
return rp
}
rp := newPromise()
pool.cache[url] = rp
pool.cacheLock.Unlock()
pool.c <- fetchWork{rp, url} // Expensive/atomic work
return rp
}
由于显而易见的原因,它用于不同类型的多个地图。
也许这是一个糟糕的解决方案?
免责声明:来自 How to test unlikely concurrent scenarios? 的代码相同,抱歉。