Cache read blocks forever
Review this Go cache with a read-then-upgrade pattern.
What's the concurrency bug?
What a strong answer looks like
Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.
0:00 of about 40 min
Mark a line and say what kind of problem it is.0 findings
1type Cache struct {
2 mu sync.RWMutex
3 data map[string]int
4}
5
6func (c *Cache) GetOrCompute(k string) int {
7 c.mu.RLock()
8 if v, ok := c.data[k]; ok {
9 c.mu.RUnlock()
10 return v
11 }
12 // not found: upgrade to write lock while still holding the read lock
13 c.mu.Lock() // (1)
14 defer c.mu.Unlock()
15 v := compute(k)
16 c.data[k] = v
17 c.mu.RUnlock()
18 return v
19}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.
Run or narrate your approach, then ask the coach.