tinyurl is a URL shortener I wrote in Go. One file, 60 lines, a map behind a sync.RWMutex . When I wrote it I felt good about the concurrency. The shared state was guarded. There were no naked map reads. I had done the thing you are supposed to do.
Then I read it back a week later and found a race, an ignored crypto error, and a small memory leak. The mutex was never the problem. The problem was that the mutex was in the wrong place.
The map, as written
type store struct { mu sync . RWMutex m map [ string ] string }
func ( s * store ) put ( code , url string ) { s . mu . Lock ( ) ; s . m [ code ] = url ; s . mu . Unlock ( ) }
func ( s * store ) get ( code string ) ( string , bool ) { s . mu . RLock ( ) ; defer s . mu . RUnlock ( ) u , ok := s . m [ code ] return u , ok }
Enter fullscreen mode
Exit fullscreen mode
Every access goes through a method. Every method locks. Grep for s.m[ and you find two hits, both inside a critical section.…