Recognize races, deadlocks, starvation and leaks
Recognize races, deadlocks, starvation and leaks
A data race occurs when conflicting accesses to the same memory location (at least one write) are unordered by synchronization, unless all such accesses are atomic. A deadlock means tasks cannot progress because required events cannot occur. Starvation means a task repeatedly fails to obtain progress or a resource while others progress. A goroutine leak leaves a task alive after its useful lifetime, often blocked forever.
package main
import ( "fmt" "sync")
func main() { var mu sync.Mutex var wg sync.WaitGroup count := 0 wg.Add(2) for i := 0; i < 2; i++ { go func() { defer wg.Done() for j := 0; j < 100; j++ { mu.Lock() count++ mu.Unlock() } }() } wg.Wait() fmt.Println(count)}count++ reads and writes. Mutex.Lock grants exclusive access until Unlock. Use the same mutex for conflicting accesses while work is active; do not copy it after use. Wait only orders the final read, not the two writers. Run go run -race main.go with a supported race-enabled toolchain. A clean run is evidence for executed paths only, not proof of race freedom.
Expected output:
200Give waiting work a stop signal
package main
import ( "fmt" "sync")
func main() { stop := make(chan struct{}) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done(); <-stop }() close(stop) wg.Wait() fmt.Println("stopped")}Closing stop makes a waiting or later receive proceed; only main owns closing. Channels are covered fully next. Without close, main waits for Done while the worker waits for stop: deadlock. In a long-running program a blocked worker might leak without a whole-program deadlock report. Avoid circular waits, never wait for a worker while holding a lock it needs, and keep critical sections short. Exact scheduling order and fairness are not guaranteed; starvation needs observation over time.
Expected output:
stoppedTry it locally
Use three goroutines, each adding 50 to a shared count via increments protected by one mutex. Wait and print the count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency foundations 04: Recognize races, deadlocks, starvation and leaks
Check the lesson objective before moving on.
Why does Wait alone not make count++ safe in multiple workers?
A worker remains blocked after its owner no longer needs it. What is this?