skip to content

The sync and sync/atomic Packages

"Share memory by communicating" is the slogan, but real Go code still locks: a mutex around a shared map, a WaitGroup around a fan-out, Once around lazy init, an atomic around a counter. Interviewers want to see you reach for the cheapest primitive that is still correct.

part ofGo (Golang)overview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

Under a sync.RWMutex read lock you copy a slice field into a local, then RUnlock — is reading it afterwards safe?

level: middleimportance: nice to knowfreq 30%

basics

~20 s

Only if writers replace the whole slice instead of writing into it. Assigning a slice copies the header — pointer, length and capacity — not the elements, so after RUnlock you are still reading a backing array the writer can reach.

open as a page

A goroutine parked in sync.Cond.Wait ignores context cancellation — how do you make shutdown work?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

sync.Cond has no context-aware or deadline-aware Wait, so only Signal or Broadcast can release a parked goroutine. Shutdown must set a closed flag under c.L and then Broadcast, with every waiter re-checking that flag after Wait returns.

open as a page

A metrics gauge counts entries by ranging a sync.Map — why is that count never exactly right?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

sync.Map has no Len, and its Range takes no snapshot: it never blocks the map's other methods, so entries stored or deleted mid-walk may or may not be visited. The number mixes several moments — an estimate, not a count.

open as a page

When is sync.Mutex.TryLock the right tool, and why are correct uses of it rare?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

TryLock takes a sync.Mutex only if it is free and reports whether it succeeded, never blocking. It fits best-effort work that is genuinely fine to skip, such as a diagnostic snapshot. Most other uses hide a design problem.

open as a page

Why does a sync.Pool of bytes.Buffers keep memory high after one huge payload, and what is the fix?

level: seniorimportance: nice to knowfreq 33%

basics

~20 s

A bytes.Buffer that grew to hold a huge payload keeps that backing array when it is put back, so the pool now recycles giant buffers for ordinary work. The fix is to skip Put for any buffer whose Cap exceeds a threshold.

open as a page

showing 31–35 of 35