Menu

1 / 2

A mutex is enough. Until the check and the write are in different locks.

DEV Community: go·Marcus Beauregard·16 days ago
#Er3odrBB
#devtogo#devto#dev#code#string
Long article (937 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.