Race Conditions & Critical Sections
Definition
Race condition
- In plain English
- A race condition is a bug where the result depends on the unpredictable timing of concurrent tasks.
- Think of it like
- It is like two people booking the last hotel room on different laptops at the same second.
Data race
- In plain English
- A data race is when two goroutines access the same variable at the same time and at least one is writing, without coordination.
- Think of it like
- It is like two people writing on the same line of a whiteboard at once.
Critical section
- In plain English
- A critical section is a piece of code that must not be run by more than one goroutine at a time.
- Think of it like
- It is like a single-person changing room.
Why it exists
A vote counter should reach 1,000. Under load, some increments disappear.
count++ reads, adds and writes. Two goroutines can read 41 and both write 42, losing one vote.
How it works
Race detector
- In plain English
- The race detector is a Go tool, enabled with -race, that reports data races while your program or tests run.
- Think of it like
- Like a smoke alarm for timing bugs.
G1 and G2 each read 41 from Count, then both write 42.
package main
import (
"fmt"
"sync"
)
func main() {
count := 0
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() { defer wg.Done(); count++ }()
}
wg.Wait()
fmt.Println(count)
}
WARNING: DATA RACE
Read at ...
Previous write at ...- A check followed by a change also needs coordination.
- A data race does not require two instructions to execute at the exact same instant.
- The detector observes executed paths; a clean run cannot prove every path safe.
Examples
Find missing votes
Many viewers vote together. An unprotected total can lose votes.
package main
import (
"fmt"
"sync"
)
func main() {
count := 0
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() { defer wg.Done(); count++ }()
}
wg.Wait()
fmt.Println(count)
}
The printed count varies and may sometimes be correct. A correct count does not make the program race-free.
The insight
Shared read-modify-write operations need coordination.
Oversell the final seat
Two buyers can both pass the last-seat check. Neither reserves the seat during that check.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
seats := 1
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if seats > 0 {
time.Sleep(10 * time.Millisecond)
seats--
fmt.Println("sold")
}
}()
}
wg.Wait()
fmt.Println("remaining", seats)
}
The pause makes overlapping checks more likely. It does not guarantee a particular order.
The insight
Protect the check and change as one operation.
Clashing map updates
Two order takers update one map. The map has no protection.
package main
import (
"fmt"
"sync"
)
func main() {
orders := make(map[int]int)
var wg sync.WaitGroup
for worker := 0; worker < 2; worker++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 10000; i++ {
orders[i] = i
}
}()
}
wg.Wait()
fmt.Println(len(orders))
}
Go may report fatal error: concurrent map writes. A crash is not guaranteed; run with -race to detect executed conflicts.
The insight
Go's built-in maps need protection when writers overlap other accesses.
Trade-offs
Pros
- Direct access avoids copying large data.
- Shared data can reduce duplicate storage.
Cons
- Timing changes can corrupt results.
- Concurrent map writes can crash.
Use when
- Several tasks truly need one value.
- Every conflicting access has protection.
Avoid when
- Each task can own its input.
- Passing results avoids shared writes.
Quick check
Takeaways
- Race conditions make results depend on timing.
- Protect both read-modify-write and check-then-act operations.
- Run programs and tests with -race.