Diagnose unsynchronized reads and writes
Diagnose unsynchronized reads and writes
A data race is a memory-ordering defect, not merely surprising output. Identify the shared location, conflicting accesses and missing happens-before path. Even a machine-word-sized read is not a substitute for synchronization. Races on multiword values such as slice descriptors can corrupt their internal consistency.
package main
import ( "fmt" "sync")
func main() { var mu sync.Mutex var wg sync.WaitGroup count := 0 for i := 0; i < 2; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < 100; j++ { mu.Lock() count++ mu.Unlock() } }() } wg.Wait() fmt.Println(count)}Without the lock, two increments contain conflicting reads and writes. WaitGroup alone only orders completion relative to the final read, not workers relative to each other. Save this example as main.go and run go run -race main.go using a supported local race toolchain. A clean run is evidence about executed paths, not proof for every input or schedule.
Expected output:
200Replace sharing with independent results
package main
import ( "fmt")
func main() { results := make(chan int, 2) go func() { results <- 100 }() go func() { results <- 100 }() fmt.Println(<-results + <-results)}Each worker sends its result; only main combines them. Avoid fixes based on sleep or checking a plain boolean in a loop. A concurrent ordinary read conflicts with a write even when the writer seems to finish first. Use a documented synchronization contract. Race freedom alone does not establish business invariants or deadlock freedom.
Expected output:
200Try it locally
Use atomic.Int64 for two workers each incrementing 50 times. Wait and print 100.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 08: Diagnose unsynchronized reads and writes
Check the lesson objective before moving on.
Why does WaitGroup alone not make two concurrent increments safe?
What does a clean race-detector run establish?