Read-Write Mutexes
Start with Read-Write Mutexes
In this lesson, explore read-write 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 read-write mutexes.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
sync.RWMutex allows multiple readers to hold RLock together, or one writer to hold Lock exclusively. It is useful only when the workload benefits from shared reads.
Do not attempt to upgrade an existing RLock into Lock; that can deadlock. Always unlock using the corresponding method.
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"
)
type Counter struct {
mu sync.RWMutex
value int
}
func (c *Counter) Get() int { c.mu.RLock(); defer c.mu.RUnlock(); return c.value }
func (c *Counter) Add() { c.mu.Lock(); defer c.mu.Unlock(); c.value++ }
func main() {
var c Counter
c.Add()
c.Add()
fmt.Println("Value:", c.Get())
}
Output
Value: 2Trace what the program does
Add acquires the exclusive write lock twice in sequence. Get uses the read lock to safely return 2.
Avoid common mistakes
- A read lock must not be used while mutating protected data.
- RWMutex is not universally faster than Mutex.
Try it yourself
Spawn three goroutines that call Get while a separate goroutine updates using Add; wait for all.
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 Read-Write 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.