Go mutex programs protect shared data when many goroutines read and write it at the same time, and worker pools control how many goroutines do the work. Together with context, these are the tools you use to build safe, fast backend services. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering safe counters, caches, worker pools, timeouts and cancellation.
You should first finish our Go goroutine programs and Go channel programs. For the theory, read WaitGroup and Mutex explained, the Go worker pool pattern and the Go context guide. All programs were tested on Go 1.27.
What are Go Mutex Programs?
Go mutex programs use sync.Mutex, which is a lock. Before touching shared data, a goroutine calls Lock. When it is done, it calls Unlock. While one goroutine holds the lock, every other goroutine that calls Lock waits its turn.
Think of a single bathroom key in an office. Only the person holding the key can go in. Everyone else waits at the door until the key comes back. A mutex is that key, and the shared data is the bathroom.
Why Go Mutex Programs Matter
When two goroutines update the same variable at the same time, updates can be lost. This bug is called a data race, and it causes wrong totals, broken maps and random crashes. Go mutex programs and worker pools prevent these bugs and keep resource use under control.
- Correct results: counters, balances and caches stay accurate.
- Controlled load: a worker pool limits how many jobs run at once.
- Clean shutdown:
contexttells every worker to stop on a timeout or cancel. - Interviews: worker pools and race fixes are among the most asked Go programs.
How Go Mutex Programs Work
A data race happens because count++ is really three steps: read, add, write. Two goroutines can both read 5, both add 1 and both write 6, losing one update. A mutex makes the three steps happen as one, because only one goroutine is inside the locked section at a time.

The table below lists the tools in this post.
| Tool | Package | Use it for |
|---|---|---|
| sync.Mutex | sync | One goroutine at a time |
| sync.RWMutex | sync | Many readers or one writer |
| atomic.Int64 | sync/atomic | Fast counters and flags |
| sync.Map | sync | Special caches with stable keys |
| Worker pool | channels + WaitGroup | Fixed number of workers |
| context.WithTimeout | context | Stop work after a time limit |
| context.WithCancel | context | Stop work on demand |
Lock-Based Go Mutex Programs
These first Go mutex programs fix data races with locks and atomics. Two short names appear in almost every program: mu is the mutex, and wg is the wait group.
Program 1: Safe Counter with a Mutex
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex // mu is the mutex (the lock)
var wg sync.WaitGroup // wg is a wait group: it waits for goroutines to finish
count := 0
for range 1000 { // repeat 1000 times
// wg.Go starts the function in a new goroutine and calls Done for you (Go 1.25+)
wg.Go(func() {
mu.Lock() // wait for the key
defer mu.Unlock() // defer gives the key back when this function ends
count++ // only one goroutine runs this line at a time
})
}
wg.Wait() // wait until all 1000 goroutines are done
fmt.Println("count:", count)
}
count: 1000
Here is what happens. Each of the 1000 goroutines takes the lock, adds 1 and gives the lock back. So no update is lost, and the count is always 1000. Without Lock and Unlock, the count would often be below 1000, and go run -race would report a data race. Read our Go race detector guide to see that report.
Program 2: The Classic Way with wg.Add and wg.Done
package main
import (
"fmt"
"sync"
)
// addMoney adds amount to the shared total while holding the lock.
func addMoney(total *int, amount int, mu *sync.Mutex, wg *sync.WaitGroup) {
defer wg.Done() // tell the wait group this goroutine is finished
mu.Lock()
*total += amount // *total means "the int that this pointer points to"
mu.Unlock()
}
func main() {
var mu sync.Mutex
var wg sync.WaitGroup
total := 0
amounts := []int{100, 250, 50}
for _, amount := range amounts {
wg.Add(1) // one more goroutine to wait for
go addMoney(&total, amount, &mu, &wg) // & passes a pointer, so all share the same values
}
wg.Wait()
fmt.Println("wallet total:", total)
}
wallet total: 400
This program does the same job as Program 1 in the older style. You call wg.Add(1) before each goroutine starts. Then each goroutine calls wg.Done() when it finishes. You will see this style in a lot of existing Go code, so it is good to know both.
Program 3: Atomic Counter Without a Lock
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var visits atomic.Int64 // a number that is safe to use from many goroutines
var wg sync.WaitGroup
for range 500 {
wg.Go(func() {
visits.Add(1) // one CPU instruction, no lock needed
})
}
wg.Wait()
fmt.Println("visits:", visits.Load()) // Load reads the current value safely
}
visits: 500
Each goroutine adds 1 with visits.Add(1), and the CPU does that in one safe step. So you need no mutex at all. Atomics are faster than a mutex for a single number. For anything bigger, like a map or two related fields, use a mutex.
Program 4: Use defer to Unlock on Every Return
package main
import (
"fmt"
"sync"
)
var mu sync.Mutex
var stock = 2 // tickets left, shared by everyone
// buyTicket sells one ticket if any are left.
func buyTicket(name string) {
mu.Lock()
defer mu.Unlock() // runs on every return below, so we never forget it
if stock == 0 {
fmt.Println(name + ": sold out") // + joins two strings
return // early return: defer still unlocks
}
stock--
fmt.Println(name + ": got a ticket")
}
func main() {
buyTicket("Asha")
buyTicket("Ravi")
buyTicket("Meera")
}
Asha: got a ticket
Ravi: got a ticket
Meera: sold out
The function has two ways out: the sold-out return and the normal end. If you wrote mu.Unlock() by hand, you would need it in both places. With defer mu.Unlock(), Go unlocks for you whichever way the function ends.
Program 5: A Bank Account Struct with Its Own Mutex
package main
import (
"errors"
"fmt"
"sync"
)
// Account holds a balance and the lock that protects it.
type Account struct {
mu sync.Mutex // protects balance
balance int
}
// Deposit adds money to the account.
func (account *Account) Deposit(amount int) {
account.mu.Lock()
defer account.mu.Unlock() // unlock even if the code below panics
account.balance += amount
}
// Withdraw takes money out, or returns an error if there is not enough.
func (account *Account) Withdraw(amount int) error {
account.mu.Lock()
defer account.mu.Unlock()
if amount > account.balance {
return errors.New("insufficient funds")
}
account.balance -= amount
return nil // nil means "no error"
}
// Balance returns the current balance.
func (account *Account) Balance() int {
account.mu.Lock()
defer account.mu.Unlock()
return account.balance
}
func main() {
myAccount := &Account{balance: 1000} // & gives a pointer to the new Account
var wg sync.WaitGroup
for range 100 {
wg.Go(func() { myAccount.Deposit(10) })
wg.Go(func() { myAccount.Withdraw(5) })
}
wg.Wait()
fmt.Println("final balance:", myAccount.Balance())
}
final balance: 1500
100 deposits of 10 add 1000, and 100 withdrawals of 5 remove 500, so the result is always 1500. Every method locks first, so two goroutines never change balance together. Keeping the mutex inside the struct, next to the data it guards, is the normal Go style.
Program 6: A Read-Heavy Cache with RWMutex
package main
import (
"fmt"
"sync"
)
// Cache is a map that many goroutines can read at the same time.
type Cache struct {
mu sync.RWMutex
data map[string]string
}
// Get looks up a key. ok is true if the key was found.
func (cache *Cache) Get(key string) (string, bool) {
cache.mu.RLock() // many readers can hold RLock together
defer cache.mu.RUnlock()
value, ok := cache.data[key]
return value, ok
}
// Set stores a value under a key.
func (cache *Cache) Set(key, value string) {
cache.mu.Lock() // a writer waits for all readers, then blocks them
defer cache.mu.Unlock()
cache.data[key] = value
}
// allTrue reports whether every item in the slice is true.
func allTrue(results []bool) bool {
for _, result := range results {
if !result {
return false
}
}
return true
}
func main() {
countries := &Cache{data: map[string]string{}}
countries.Set("IN", "India")
var wg sync.WaitGroup
hits := make([]bool, 50) // one slot per reader, so readers never share a slot
for i := range 50 {
wg.Go(func() {
_, hits[i] = countries.Get("IN") // 50 readers at once
})
}
wg.Wait()
fmt.Println("all hits:", allTrue(hits))
}
all hits: true
You store one country, and then 50 goroutines read it at the same time. RWMutex lets all those readers in together, which is faster for caches that are read far more often than written. A writer still gets the data alone, because Lock waits for every reader to leave.
Worker Pool Go Mutex Programs
A worker pool starts a fixed number of goroutines that pull jobs from one channel. It is one of the most asked Go programs in interviews, and many real Go mutex programs pair a pool with a lock or an atomic counter.
Program 7: A Basic Worker Pool
package main
import (
"fmt"
"sync"
)
// Result is the answer for one job.
type Result struct {
Job int
Square int
}
// worker takes jobs until the jobs channel is closed.
func worker(jobs <-chan int, results chan<- Result, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs { // keep taking jobs until the channel is closed
results <- Result{Job: job, Square: job * job}
}
}
func main() {
jobs := make(chan int, 10)
results := make(chan Result, 10)
var wg sync.WaitGroup
// Step 1: start 3 workers.
for range 3 {
wg.Add(1)
go worker(jobs, results, &wg)
}
// Step 2: send 6 jobs, then close so workers know there are no more.
for job := 1; job <= 6; job++ {
jobs <- job
}
close(jobs)
// Step 3: wait for the workers, then close results.
wg.Wait()
close(results)
// Step 4: put each answer in the slot for its job number.
squares := make([]int, 7)
for result := range results {
squares[result.Job] = result.Square
}
for job := 1; job <= 6; job++ {
fmt.Printf("job %d -> %d\n", job, squares[job])
}
}
job 1 -> 1
job 2 -> 4
job 3 -> 9
job 4 -> 16
job 5 -> 25
job 6 -> 36
Which worker takes which job changes every run. So each answer goes into the slot for its job number, and you print the slots in order. The pattern is always the same: start workers, send jobs, close jobs, wait, close results.
Program 8: Limit Concurrency with a Semaphore Channel
package main
import (
"fmt"
"sync"
"time"
)
func main() {
slots := make(chan struct{}, 2) // a semaphore: at most 2 tasks at once
var mu sync.Mutex
var wg sync.WaitGroup
running := 0 // tasks working right now
peak := 0 // the highest value running ever reached
for range 6 {
wg.Go(func() {
slots <- struct{}{} // take a slot (waits if both are taken)
defer func() { <-slots }() // give the slot back at the end
mu.Lock()
running++
if running > peak {
peak = running
}
mu.Unlock()
time.Sleep(20 * time.Millisecond) // pretend to work
mu.Lock()
running--
mu.Unlock()
})
}
wg.Wait()
fmt.Println("max running at once:", peak)
}
max running at once: 2
The buffered channel works like a car park with two spaces. A goroutine can only start work after it gets a space, so no more than two ever run together. The mutex protects running and peak, because six goroutines update them.
Context in Go Mutex Programs
context tells goroutines when to stop, either after a timeout or when you cancel. Real Go mutex programs almost always use it, so a stuck worker never holds a lock forever. In the code, ctx is the usual short name for a context.
Program 9: Stop a Slow Task with WithTimeout
package main
import (
"context"
"fmt"
"time"
)
// fetchReport waits for the work or for the caller to give up.
func fetchReport(ctx context.Context, delay time.Duration) (string, error) {
select {
case <-time.After(delay): // the work finished
return "report ready", nil
case <-ctx.Done(): // the caller gave up
return "", ctx.Err()
}
}
func main() {
delays := []time.Duration{50 * time.Millisecond, 500 * time.Millisecond}
for _, delay := range delays {
// ctx gives up after 100ms; cancel frees its timer.
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
report, err := fetchReport(ctx, delay) // err is the error value, nil if all went well
cancel() // always call cancel to free resources
if err != nil {
fmt.Println(delay, "->", err) // timed out: print only the reason
continue
}
fmt.Println(delay, "->", report, err)
}
}
50ms -> report ready <nil>
500ms -> context deadline exceeded
The 50ms task finishes before the 100ms limit, so you get the report. The 500ms task is too slow. When the deadline passes, ctx.Done() closes and ctx.Err() explains why. The cancel() call frees the timer behind the context.
Program 10: Cancel All Workers on Demand
package main
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var processed atomic.Int64
var wg sync.WaitGroup
for range 3 {
wg.Go(func() {
for { // loop until told to stop
select {
case <-ctx.Done(): // stop signal for every worker
return
default: // no stop signal yet, so do one piece of work
processed.Add(1)
time.Sleep(10 * time.Millisecond)
}
}
})
}
time.Sleep(55 * time.Millisecond)
cancel() // tell all workers to stop
wg.Wait() // wait until they really have stopped
fmt.Println("stopped cleanly, some work done:", processed.Load() > 0)
fmt.Println("reason:", ctx.Err())
}
stopped cleanly, some work done: true
reason: context canceled
Three workers keep doing small pieces of work. After 55ms, one cancel call closes ctx.Done() for all of them, so each worker returns. This is how servers shut down workers during a deploy.
Program 11: sync.Map for a Shared Registry
package main
import (
"fmt"
"sync"
)
func main() {
var sessions sync.Map // safe for concurrent use without your own mutex
var wg sync.WaitGroup
for _, user := range []string{"asha", "ravi", "meera"} {
wg.Go(func() {
sessions.Store(user, "logged-in")
})
}
wg.Wait()
status, ok := sessions.Load("ravi") // ok is true if the key was found
fmt.Println(status, ok)
// Range calls the function once for every key and value.
count := 0
sessions.Range(func(key, value any) bool {
count++
return true // true means "keep going"
})
fmt.Println("sessions:", count)
}
logged-in true
sessions: 3
Three goroutines store a session each, with no mutex of your own. Then Load reads one key, and Range counts all of them. sync.Map is built for keys that are written once and read many times. For most other cases, a normal map with a mutex is simpler and just as fast.
Most Asked Interview Go Mutex Programs
Program 12: Fix the Classic Race in a Map
package main
import (
"fmt"
"sync"
)
// Counter counts page visits safely.
type Counter struct {
mu sync.Mutex
hits map[string]int
}
// Inc adds one visit for the given page.
func (counter *Counter) Inc(page string) {
counter.mu.Lock()
counter.hits[page]++ // map writes from many goroutines MUST be locked
counter.mu.Unlock()
}
func main() {
visits := Counter{hits: map[string]int{}}
var wg sync.WaitGroup
pages := []string{"/home", "/blog", "/home"}
for range 100 {
for _, page := range pages {
wg.Go(func() { visits.Inc(page) })
}
}
wg.Wait()
fmt.Println(visits.hits["/home"], visits.hits["/blog"])
}
200 100
Each round visits /home twice and /blog once, and there are 100 rounds. So the counts are 200 and 100. Without the mutex, Go may crash with “fatal error: concurrent map writes”. Plain maps are never safe for concurrent writes.
Program 13: Worker Pool That Stops on the First Error
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
jobs := make(chan int)
var once sync.Once // once.Do runs its function only one time
var firstErr error
var wg sync.WaitGroup
// Step 1: start 3 workers.
for range 3 {
wg.Go(func() {
for job := range jobs {
if job == 4 { // pretend job 4 fails
once.Do(func() {
firstErr = fmt.Errorf("job %d: bad input", job)
cancel() // stop the producer and other workers
})
return
}
}
})
}
// Step 2: send jobs, but stop as soon as the context is cancelled.
for job := 1; job <= 10; job++ {
if ctx.Err() != nil { // not nil means cancel was called
break
}
select {
case jobs <- job: // a worker took the job
case <-ctx.Done(): // cancelled while waiting
}
}
// Step 3: close jobs, wait for the workers and print the error.
close(jobs)
wg.Wait()
fmt.Println("error:", firstErr)
}
error: job 4: bad input
When a worker gets job 4, it saves the error and calls cancel. sync.Once keeps only the first error, even if many workers fail. The producer sees the cancel and stops sending. The golang.org/x/sync/errgroup package wraps this whole pattern into a few lines.
Program 14: Avoid Deadlock with Lock Ordering
package main
import (
"fmt"
"sync"
)
// Wallet has an ID, a balance and its own lock.
type Wallet struct {
ID int
mu sync.Mutex
Balance int
}
// transfer always locks the wallet with the smaller ID first.
// If two transfers lock in opposite orders, they can deadlock.
func transfer(from, to *Wallet, amount int) {
// Step 1: decide the lock order.
first := from
second := to
if to.ID < from.ID {
first = to
second = from
}
// Step 2: lock both wallets in that order.
first.mu.Lock()
defer first.mu.Unlock()
second.mu.Lock()
defer second.mu.Unlock()
// Step 3: move the money.
from.Balance -= amount
to.Balance += amount
}
func main() {
walletOne := &Wallet{ID: 1, Balance: 500}
walletTwo := &Wallet{ID: 2, Balance: 500}
var wg sync.WaitGroup
for range 50 {
wg.Go(func() { transfer(walletOne, walletTwo, 3) })
wg.Go(func() { transfer(walletTwo, walletOne, 2) })
}
wg.Wait()
total := walletOne.Balance + walletTwo.Balance
fmt.Println(walletOne.Balance, walletTwo.Balance, total)
}
450 550 1000
Both directions lock wallet 1 before wallet 2, so two transfers can never wait on each other in a circle. Wallet 1 sends 3 fifty times and gets 2 back fifty times, so it ends at 450. The total money always stays 1000.
Mutex vs Channels in Go Mutex Programs
Both tools make concurrent code safe. Go mutex programs share memory under a lock, while channel programs pass data between goroutines. The diagram and table below compare them.

| Feature | Mutex | Channel |
|---|---|---|
| Best for | Guarding shared state | Passing data and signals |
| Example | Counter, cache, balance | Job queue, results, stop signal |
| Ownership | Shared by many | Moves from sender to receiver |
| Risk | Forgetting Unlock, deadlocks | Deadlocks, leaks, closed channel panics |
| Speed for a counter | Fast | Slower |
A simple rule helps: if goroutines share a value, use a mutex. If they hand work to each other, use a channel.
Common Mistakes in Go Mutex Programs
- Forgetting Unlock: every other goroutine then waits forever, so use
defer mu.Unlock(). - Locking twice in one goroutine: Go mutexes are not re-entrant, so a second
Lockdeadlocks. - Copying a struct with a mutex: the copy has its own lock, so use pointer receivers.
- Forgetting cancel(): a context without
cancelleaks a timer until it expires. - Closing the jobs channel from a worker: only the producer should close it.
Best Practices for Go Mutex Programs
- Keep the locked section small, only around the shared data.
- Put the mutex next to the data it protects, inside the same struct.
- Use atomics for single counters and a mutex for anything larger.
- Pass context.Context as the first argument of functions that may be slow.
- Run tests with -race to catch the races you missed.
Go Mutex Programs Interview Questions and Answers
These are the concurrency safety questions interviewers ask most, and they build on the Go mutex programs above. Each program is complete, with real output from Go 1.27.
Mutex Questions
Q1. What happens if you lock a mutex twice in the same goroutine?
package main
import "sync"
func main() {
var mu sync.Mutex
mu.Lock()
mu.Lock() // waits for itself forever
}
fatal error: all goroutines are asleep - deadlock!
Go mutexes are not re-entrant. A function that holds a lock must not call another function that takes the same lock.
Q2. What is the difference between Mutex and RWMutex?
Mutex lets one goroutine in at a time. RWMutex lets many readers in together with RLock, but a writer with Lock gets the data alone. Use RWMutex only when reads greatly outnumber writes.
Q3. Why should a struct with a mutex use pointer receivers?
A value receiver copies the struct, including the mutex. Each copy has its own lock, so the lock no longer protects the shared data. go vet warns about this.
Atomic and Context Questions
Q4. When should you use sync/atomic instead of a mutex?
For single values like counters and flags, atomics are faster and simpler. When several fields must change together, such as a balance and a history list, use a mutex.
Q5. What does this program print?
package main
import (
"context"
"fmt"
"time"
)
func main() {
// Case 1: cancel before the time limit.
longCtx, cancelLong := context.WithTimeout(context.Background(), time.Hour)
cancelLong()
<-longCtx.Done() // already closed, so this does not wait
fmt.Println(longCtx.Err())
// Case 2: let the time limit run out.
shortCtx, cancelShort := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancelShort()
<-shortCtx.Done() // waits about 10ms
fmt.Println(shortCtx.Err())
}
context canceled
context deadline exceeded
Calling cancel early gives “context canceled”. Letting the time run out gives “context deadline exceeded”. Code can check which one happened with errors.Is.
Q6. What does this program print?
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var ready atomic.Bool // starts as false
fmt.Println(ready.Load())
ready.Store(true)
// CompareAndSwap(old, new): if the value is old, set it to new.
swapped := ready.CompareAndSwap(true, false)
fmt.Println(swapped, ready.Load())
}
false
true false
The flag starts as false. After Store(true), it equals the old value true, so CompareAndSwap changes it to false and returns true. It is the building block of many lock-free tricks.
Worker Pool Questions in Go Mutex Programs
Q7. How many workers should a pool have?
For CPU-heavy work, start with runtime.NumCPU() workers. For work that waits on the network or disk, you can use more, then measure and adjust.
Q8. Why close the jobs channel?
Closing tells every worker’s for range jobs loop to stop after the last job. Without it, workers wait forever and wg.Wait() never returns.
Q9. Why do worker pool results come back in random order?
Workers run at the same time and finish at different speeds. If order matters, attach the job index to each result and sort, or write each result into its own slot.
Q10. What does this program print?
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int, 5)
var mu sync.Mutex
var wg sync.WaitGroup
total := 0
for range 2 { // two workers share one total
wg.Go(func() {
for job := range jobs {
mu.Lock()
total += job
mu.Unlock()
}
})
}
for job := 1; job <= 5; job++ {
jobs <- job
}
close(jobs)
wg.Wait()
fmt.Println(total)
}
15
Two workers add jobs 1 to 5 into one total. The mutex makes sure no addition is lost, so the answer is always 15.
Q11. What is a deadlock, and how do you avoid one?
A deadlock is when goroutines wait on each other forever, for example A holds lock 1 and waits for lock 2 while B holds lock 2 and waits for lock 1. Avoid it by always taking locks in the same order, as in Program 14, and by holding locks for as short a time as possible.
Q12. What does go run -race do?
It builds the program with a race detector that watches every memory access. If two goroutines touch the same memory without sync and one of them writes, it prints a report with both stack traces.
Practice Task
To practise Go mutex programs, build an image resize simulator: a worker pool of 3 workers processes 10 “images”, each taking a fake 30 ms, with a total time limit of 200 ms using context.WithTimeout. Print how many images finished before the deadline. Hint: count finished jobs with an atomic.Int64 and check ctx.Done() inside the worker loop.
Official Resources
Quick Recap
- Go mutex programs use
LockandUnlockso only one goroutine changes shared data at a time. RWMutexallows many readers, and atomics are best for single counters.- A worker pool starts a fixed number of workers that pull jobs from a channel.
context.WithTimeoutandWithCanceltell every worker when to stop.- Avoid deadlocks by locking in a fixed order and never locking twice in one goroutine.
What’s Next?
Next, we write code that works for many types at once. Read Go generics programs with output, with Map, Filter, Reduce and a generic stack. For more practice, see the Go sync package interview questions.


