Level: AdvancedInterview

Go Sync Package Questions: Mutex, WaitGroup and Once (Part 16)

Updated 9 min read
Go Sync Package Questions featured image: mutex, once and atomic cards

These Go sync package questions cover Mutex, RWMutex, WaitGroup, Once, sync/atomic, sync.Map, sync.Pool and sync.Cond. We gathered them from public interview lists, coding rounds and community threads. Then we rewrote them in plain words and grouped them by tool.

This post is questions only, so answer each one in your own words first. When you need help, read Go sync package: WaitGroup and Mutex and Go race detector. Also, finish Part 15 on channels first, because you should know when a channel fits better than a lock.

How to Use These Go Sync Package Questions

Answer each of these Go sync package questions out loud, then write a tiny program and run it with -race. Lock bugs usually appear only under load, so small tests with many goroutines help a lot. Finally, try the scenario questions, since they come from real production issues.

The table below lists each section and its number of questions.

SectionWhat it testsQuestions
Mutex basicsLock, defer and copy rules15
RWMutex and designReaders, writers and lock order14
WaitGroup and OnceWaiting for work and running once15
sync/atomicAtomic types, CAS and Pointer14
Map, Pool and CondSpecial tools for narrow cases15
Sync coding tasksClassic interview programs14
Go Sync Package Questions diagram showing six question areas from Mutex to coding tasks
The six areas covered in this question list, from Mutex to coding tasks.

Go Sync Package Questions on Mutex

Before you answer, study Go sync package: WaitGroup and Mutex. These Go sync package questions start with the Mutex, because most shared state in Go uses one.

  1. What is a sync.Mutex, and what problem does it solve?
  2. Why is the zero value of a Mutex ready to use?
  3. Why should you release a lock with defer right after you take it?
  4. When is it better not to use defer, for example in a tight loop?
  5. Is a Go Mutex reentrant, and what happens when one goroutine locks it twice?
  6. Why must you never copy a Mutex after first use?
  7. How does go vet catch a copied lock?
  8. Should a Mutex be a named field or an embedded field, and why?
  9. Where should the Mutex sit in a struct, next to the fields it guards?
  10. What does TryLock do, and why do the docs say to use it rarely?
  11. What is starvation mode in the Go Mutex?
  12. How do you keep the critical section as small as possible?
  13. Why is calling an unknown callback while holding a lock risky?
  14. Scenario: when a method with a value receiver locks a Mutex and the data still races, what went wrong?
  15. Scenario: when a service slows down because many goroutines wait for one lock, how would you find and fix it?

Go Sync Package Questions on RWMutex and Lock Design

Before you answer, study Go in-memory cache with TTL, because a cache is the classic place for an RWMutex. These Go sync package questions test design, so explain the trade-off behind each answer.

  1. What is an RWMutex, and how do RLock and Lock differ?
  2. When does an RWMutex beat a plain Mutex, and when is it slower?
  3. What happens to new readers while a writer waits for the lock?
  4. Can you upgrade a read lock to a write lock in Go?
  5. Why can a recursive read lock deadlock when a writer is waiting?
  6. What is lock ordering, and how does it prevent deadlocks?
  7. How does sharding a map into many locked parts reduce waiting?
  8. When should you use a channel instead of a lock?
  9. How do you protect a slice that many goroutines append to?
  10. Why should getters return copies of slices instead of the guarded slice itself?
  11. How do you test that a type is safe for concurrent use?
  12. How do mutex profiles in pprof show lock waiting time?
  13. Scenario: when a read-heavy cache uses a Mutex and CPU is high, how would you decide whether to switch to RWMutex?
  14. Scenario: when two services each hold one lock and wait for the other, how would you redesign the locking?

Go Sync Package Questions on WaitGroup and Once

Before you answer, study Go worker pool pattern. WaitGroup and Once look simple, yet many Go sync package questions hide traps inside them.

  1. What do Add, Done and Wait do on a WaitGroup?
  2. Why must Add happen before the goroutine starts?
  3. What happens when the code calls Done more times than Add?
  4. Can you reuse a WaitGroup after Wait returns?
  5. What does WaitGroup.Go add in Go 1.25, and how does it simplify code?
  6. How do you wait for a WaitGroup with a timeout?
  7. What does sync.Once guarantee, even with many goroutines?
  8. What happens if the function passed to Once.Do panics?
  9. Can a Once run its function again after an error, and what is the workaround?
  10. What do sync.OnceFunc, sync.OnceValue and sync.OnceValues add since Go 1.21?
  11. Why is Once a good fit for lazy setup of a shared client?
  12. How is Once different from an init function?
  13. Why does calling Once.Do from inside the same function deadlock?
  14. Scenario: when a lazy database connection must open once but can fail, how would you design it?
  15. Scenario: when a program sometimes exits before the last worker logs its result, what would you check?

Go Sync Package Questions on sync/atomic

Before you answer, study Go race detector again. Atomics are fast but easy to misuse, so these Go sync package questions ask where they stop being enough.

  1. What does the sync/atomic package give you?
  2. When is an atomic counter better than a Mutex?
  3. What types did Go 1.19 add, such as atomic.Int64 and atomic.Bool?
  4. Why are the new atomic types safer than the old functions on plain ints?
  5. What does CompareAndSwap do, and how do you build a retry loop with it?
  6. How does atomic.Pointer help you swap a whole config at once?
  7. What is atomic.Value, and what limit does it have on types?
  8. Why can two separate atomic operations still race as a pair?
  9. How do atomics fit into the Go memory model?
  10. Why is a 64-bit atomic on 32-bit platforms a special case in old code?
  11. Can you mix atomic and normal reads on the same variable?
  12. How do you read a flag that another goroutine sets with an atomic store?
  13. Scenario: when a hot counter with a Mutex shows up in a CPU profile, how would you replace it?
  14. Scenario: when a feature flag must change at run time without a restart, how would you store it?

sync.Map, sync.Pool and sync.Cond

Before you answer, study Go garbage collector and memory. These three tools solve narrow problems, so these Go sync package questions test when to pick them.

  1. What is sync.Map, and how is it different from a map with a Mutex?
  2. For which two access patterns do the docs suggest sync.Map?
  3. Why does sync.Map use any for keys and values, and what does that cost?
  4. What do LoadOrStore and LoadAndDelete do?
  5. How do you count the items in a sync.Map?
  6. What is sync.Pool, and what kind of objects belong in it?
  7. Why can the garbage collector drop objects from a Pool at any time?
  8. Why should you reset a buffer before you put it back in a Pool?
  9. When does a Pool make things slower instead of faster?
  10. What is sync.Cond, and what do Wait, Signal and Broadcast do?
  11. Why must Wait run inside a loop that checks the condition?
  12. Why do many Go developers use channels instead of sync.Cond?
  13. How would you build a bounded queue with sync.Cond?
  14. Scenario: when a JSON service allocates a new buffer for every request, how would you reuse them?
  15. Scenario: when a team replaces every map with sync.Map, how would you review the change?

Go Sync Package Questions for Coding Rounds

Before you answer, write each program by hand and run it with -race. Interviewers watch where you take and release locks, not only whether the code runs.

  1. Write a safe counter type with Inc and Value methods.
  2. Build a thread-safe cache with Get and Set using RWMutex.
  3. Fix a program that copies a struct holding a Mutex.
  4. Use sync.Once to create a single shared HTTP client.
  5. Count page hits from many goroutines with atomic.Int64.
  6. Swap a config pointer at run time with atomic.Pointer.
  7. Count unique visitors from many goroutines with sync.Map.
  8. Reuse bytes.Buffer objects with sync.Pool.
  9. Build a bounded queue with sync.Cond and two methods.
  10. Write a bank account with Deposit and Withdraw that never goes below zero.
  11. Transfer money between two accounts without deadlock.
  12. Print numbers in order from three goroutines using only a Mutex and a counter.
  13. Scenario: when an interviewer asks for a rate counter per user, how would you lock it without one global lock?
  14. Scenario: when a bank transfer locks two accounts, how would you choose the lock order?

Code Reading Questions

Read each program carefully and predict the output before you run it. Then explain the result in your own words.

package main

import (
    "fmt"
    "sync"
)

var (
    once   sync.Once
    config map[string]string
)

func loadConfig() {
    fmt.Println("loading config")
    config = map[string]string{"env": "prod"}
}

var port = sync.OnceValue(func() int {
    fmt.Println("reading port")
    return 8080
})

func main() {
    var wg sync.WaitGroup
    for range 3 {
        wg.Add(1)
        go func() {
            defer wg.Done()
            once.Do(loadConfig)
        }()
    }
    wg.Wait()
    fmt.Println(config["env"])
    fmt.Println(port(), port())
}
  1. How many times does loading config print, and why is reading config after Wait safe?
  2. What does the last line print, and how many times does reading port appear?

The second program counts hits with an atomic type and unique users with sync.Map.

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var hits atomic.Int64
    var seen sync.Map
    var wg sync.WaitGroup
    users := []string{"asha", "ravi", "asha", "meera", "ravi", "asha"}
    for _, u := range users {
        wg.Add(1)
        go func(name string) {
            defer wg.Done()
            hits.Add(1)
            seen.LoadOrStore(name, true)
        }(u)
    }
    wg.Wait()
    unique := 0
    seen.Range(func(_, _ any) bool {
        unique++
        return true
    })
    fmt.Println(hits.Load(), unique)

    var state atomic.Int32
    fmt.Println(state.CompareAndSwap(0, 1), state.CompareAndSwap(0, 2), state.Load())
}
  1. What two numbers does the first line print, and why is the result the same on every run?
  2. Why does the second CompareAndSwap return false, and what is the final state?

Quick Revision Table for the sync Package

Use the table below as a final check before your interview. It maps each tool to the job it does best.

ToolBest forWatch out for
sync.MutexGuarding shared fieldsCopying it, long critical sections
sync.RWMutexRead-heavy dataNo upgrade from read to write
sync.WaitGroupWaiting for a set of goroutinesAdd before go, never below zero
sync.OnceOne-time setupA panic still counts as done
sync/atomicCounters and flagsTwo ops are not atomic together
sync.MapStable keys, many readersType safety and counting items
sync.PoolReusing short-lived buffersObjects can vanish at GC

Also, many interviewers ask you to compare Mutex and RWMutex directly. The diagram below shows the difference side by side.

Go sync package diagram comparing Mutex with RWMutex
A Mutex lets one goroutine in at a time, while an RWMutex lets many readers in together.

Official Resources

These official pages explain the rules behind these questions.

Quick Recap

  • These Go sync package questions cover Mutex, RWMutex, WaitGroup, Once, atomics, sync.Map, Pool and Cond.
  • Release every lock with defer, and never copy a struct that holds a lock.
  • Use RWMutex only when reads clearly outnumber writes.
  • Once runs setup exactly one time, and OnceValue returns a cached result.
  • Atomic types suit single counters and flags, while a Mutex guards groups of fields.
  • Pick sync.Map and sync.Pool only for the narrow cases the docs describe.

What’s Next?

By now, you have Go sync package questions for every tool in the sync package. Study the answers in your own notes, then check them against the Go interview topics study guide.

Next up: Go context interview questions (Part 17)