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 pageshowhide
explore
- sync.Mutex4 questions
- sync.Pool and Buffer Reuse4 questions
- sync.Map4 questions
- sync.RWMutex4 questions
- sync.WaitGroup4 questions
- sync.Once and Lazy Initialization4 questions
- sync/atomic and Atomic Types4 questions
- sync.Cond3 questions
- Lock Granularity and Sharding4 questions
questions
page 2 of 2Under a sync.RWMutex read lock you copy a slice field into a local, then RUnlock — is reading it afterwards safe?
basics
~20 sOnly 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.
A goroutine parked in sync.Cond.Wait ignores context cancellation — how do you make shutdown work?
basics
~20 ssync.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.
A metrics gauge counts entries by ranging a sync.Map — why is that count never exactly right?
basics
~20 ssync.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.
When is sync.Mutex.TryLock the right tool, and why are correct uses of it rare?
basics
~20 sTryLock 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.
Why does a sync.Pool of bytes.Buffers keep memory high after one huge payload, and what is the fix?
basics
~20 sA 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.
showing 31–35 of 35