Mutexes
Start with Mutexes
In this lesson, explore mutexes through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of mutexes.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A sync.Mutex protects a critical section: only one goroutine may hold the lock at a time. Lock before accessing shared mutable state, then unlock when finished.
A mutex protects an invariant, not merely a single statement. Every writer and reader of protected state must follow the same locking discipline.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
var wg sync.WaitGroup
count := 0
for i := 0; i < 4; i++ {
wg.Add(1)
go func() { defer wg.Done(); mu.Lock(); count++; mu.Unlock() }()
}
wg.Wait()
fmt.Println("Count:", count)
}
Output
Count: 4Trace what the program does
The four workers increment shared count inside the lock. The main goroutine waits for all workers, then safely prints 4.
Avoid common mistakes
- Never copy a mutex after use.
- A mutex does not protect code that accesses the same variable without locking.
Try it yourself
Make each worker increment count twice while holding the lock; predict the new count.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Mutexes in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.