Race Detector Finds Data Races

Show the unsynchronized counter that the race detector flags under go run -race, and the mutex-guarded version that converges on the same workload.

GoData Integrity

Code

gosnippet
52 lines
package main

import (
	"fmt"
	"sync"
)

func main() {
	var counter int
	var wg sync.WaitGroup

	// 两个 goroutine 无同步地写同一个变量:
	// go run -race 会报告 DATA RACE;不带 -race 时更新可能被静默覆盖
	wg.Add(2)
	go func() {
		defer wg.Done()
		for i := 0; i < 1000; i++ {
			counter++
		}
	}()
	go func() {
		defer wg.Done()
		for i := 0; i < 1000; i++ {
			counter--
		}
	}()
	wg.Wait()
	fmt.Println("counter:", counter)

	// 正确做法:每次增量都受互斥锁保护,结果恒为 0
	var mu sync.Mutex
	var safe int
	wg.Add(2)
	go func() {
		defer wg.Done()
		for i := 0; i < 1000; i++ {
			mu.Lock()
			safe++
			mu.Unlock()
		}
	}()
	go func() {
		defer wg.Done()
		for i := 0; i < 1000; i++ {
			mu.Lock()
			safe--
			mu.Unlock()
		}
	}()
	wg.Wait()
	fmt.Println("safe:", safe)
}

The runtime narrative

What shifts is held in the function main.

The file repeats itself only inside for i := 0; i < 1000; i++. Work is dispatched on a goroutine. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Points of care

  • There is no install step, because the platform ships every API the code calls.

Applying it

The entry-point signature is func main()

The demo output is labeled (counter:, safe:); each label names the call that printed it.

Statements that matter

var wg sync.WaitGroup
var mu sync.Mutex
defer wg.Done()

Interactive Tools for This Topic

FAQ

What does Race Detector Finds Data Races print when run?
The script runs standalone; its 2 labeled outputs include `counter:`, `safe:`.